Async setSinkId

by jib1

HTML

<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
Speaker: <select id="speaker"></select><br>
<video id="video" width="160" height="120" autoplay controls></video><br>
<div id="div"></div>

JavaScript

const console = { log: msg => div.innerHTML += msg + "<br>" };
const dump = f => console.log(`${f.toString().slice(6)} = ${JSON.stringify(f())}`);
let stream;

(async () => {
  try {
    if (!("setSinkId" in video)) return console.log("No setSinkId");
//    stream = await navigator.mediaDevices.getUserMedia({video: true});
    video.srcObject = new MediaStream([tone()]);
    updateSelectors();
  } catch(e) {
    console.log(e);
  }
})();

speaker.onchange = async () => {
  try {
    await video.setSinkId(speaker.value);
  } catch (e) {
    console.log(e);
  }
};


navigator.mediaDevices.ondevicechange = () => updateSelectors();

async function updateSelectors() {
  try {
    const devices = await navigator.mediaDevices.enumerateDevices();

    for (const [s, kind, name] of [[speaker, "audiooutput", "Speaker"]]) {
      const old = s.value;
      while (s.firstChild) s.removeChild(s.firstChild);
      let i = 0;
      for (const device of devices) {
        if (device.kind != kind) continue;
        const option = document.createElement('option');
        option.value = device.deviceId;
        option.text = device.label || `${name} ${++i}`;
        s.appendChild(option);
      }
      if ([...s.options].map(({value}) => value).includes(old)) s.value = old;
    }
  } catch (e) {
    console.log(e);
  }
}

function tone() {
  const ctx = new AudioContext(), oscillator = ctx.createOscillator();
  const dst = oscillator.connect(ctx.createMediaStreamDestination());
  oscillator.start();
  return dst.stream.getAudioTracks()[0];
}