navigator.mediaDevices.enumerateDevices() does not get multiple audiooutput

2.1k views Asked by At

Project: list all media devices, then select 1 specific audio output device which is different from the default of Windows

I used enumerateDevices(), following many code examples, example here, and:

  • on Firefox: list of audioinput, videoinput, no audiooutput showed, but only 1 for each (I have 2 inputs, 3 outputs)
  • on Chrome, Brave: same list showed, also only 1 for each, and empty kind/label/id (groupId is none-empty though)

code:

function checkDevices(devices){
        (async () => {   
  await navigator.mediaDevices.getUserMedia({audio: true, video: true});   
  let devices = await navigator.mediaDevices.enumerateDevices();   
  devices.forEach(function (device) {
      console.log(device.kind + ": " + device.label + " id: " + device.groupId);//Other parameters device.kind/device.deviceId
    });
  })();
}
function checkError(err){
    console.log(err.name + ": " + err.message);
} 
navigator.mediaDevices.enumerateDevices().then(checkDevices).catch(checkError);

Can someone help?

output Firefox enter image description here

output Chrome (same on Brave) enter image description here

1

There are 1 answers

1
nphaibk On

I found the reason why the code does not work, and some workaround, maybe helpful for others on similar situation:

Reason: enumerateDevices() require both permission from the user and security by the browser (https) to correctly list the available devices. Since the code is located locally, it returns a wrong list and empty label/kind.

Some workarounds:

  1. publish the html, example, I used https://www.netlify.com/ (free); but if your project is under development, it is not convenient to reupload the html every try. Netlify allows to link to github, so the code can be auto-refreshed

  2. use online compiler like www.w3schools.com, because the code is running from a website, it works

  3. use electron to make desktop application, the code is basically the same as that for web app. don't know about electron? check this video (15min) here

Hope those help someone!