AngryHacker
AngryHacker

Reputation: 61636

How to find out which microphone device user gave permission to?

I ask user the permission to use Camera and Microphone:

await navigator.mediaDevices.getUserMedia({ audio: true, video: true });

And in Firefox, I get the following prompt:

enter image description here

Once the user gave the permission, how can I tell which Camera and Microphone was selected? The return value of getUserMedia doesn't provide much info.

Upvotes: 2

Views: 577

Answers (1)

O. Jones
O. Jones

Reputation: 108796

Once gUM has given you a stream object do something like this:

async function getAudioDeviceLabel(stream) {
  let audioDeviceLabel = 'unknown'
  const tracks = stream.getAudioTracks()
  if( tracks && tracks.length >= 1 && tracks[0] ) {
    const settings = tracks[0].getSettings()
    const chosenDeviceId = settings.deviceId
    if (chosenDeviceId) {
      let deviceList = await navigator.mediaDevices.enumerateDevices()
      deviceList = deviceList.filter(device => device.deviceId === chosenDeviceId)
      if (deviceList && deviceList.length >= 1) audioDeviceLabel = deviceList[0].label
    }
  }
  return audioDeviceLabel 
}

This gets the deviceId of the audio track of your stream, from its settings. It then looks at the list of enumerated devices to retrieve the label associated with the deviceId.

It is kind of a pain in the xxx neck to get this information.

Upvotes: 1

Related Questions