JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//static.twilio.com/libs/twiliojs/edge/twilio.js"></script>
<p>Select an audio device, then click "Connect."</p>
<!-- We'll use MediaStreamTrack.getSources to populate this select tag. -->
<select id="audioSelect"></select>
<button id="connectButton">Connect</button>
JavaScript
// First, setup the Twilio Device. You'll need to paste a token in and
// uncomment Twilio.Device.setup.
var token = 'YOUR CAPABILITY TOKEN HERE';
// Twilio.Device.setup(token);
// Then, query for audio sources.
if (typeof MediaStreamTrack === 'undefined') {
alert('This browser does not support MediaStreamTrack.\n\nTry Chrome 30 or newer.');
} else {
MediaStreamTrack.getSources(gotSources);
}
// Next, populate the audio device select box with our audio sources.
function gotSources(sourceInfos) {
sourceInfos.forEach(function(sourceInfo, i) {
if (sourceInfo.kind === 'audio') {
var option = document.createElement('option');
option.value = sourceInfo.id;
option.text = sourceInfo.label || 'Microphone ' + (i + 1);
audioSelect.appendChild(option);
}
});
updateAudioSource();
}
// This is the audioConstraints object we'll pass to Twilio.Device.connect.
var audioConstraints = {};
// When a new device is selected, update the constraints.
var audioSelect = document.getElementById('audioSelect');
function updateAudioSource() {
var audioSource = audioSelect.value;
audioConstraints.optional = [
{ sourceId: audioSource }
];
}
audioSelect.onchange = updateAudioSource;
// Finally, pass the constraints to Twilio.Device.connect when the button is
// pressed.
var connectButton = document.getElementById('connectButton');
connectButton.onclick = function() {
var clientParams = { foo: 'bar' };
Twilio.Device.connect(clientParams, audioConstraints);
};