如何找出用户授予了哪个麦克风设备的权限?

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

我请求用户允许使用相机和麦克风:

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

而在 Firefox 中,我得到以下提示:

用户授予权限后,如何判断选择了哪个摄像头和麦克风? getUserMedia 的 return 值没有提供太多信息。

一旦 gUM 给了你一个 stream 对象就做这样的事情:

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 
}

这会从其设置中获取流的音轨的 deviceId。然后它查看枚举设备列表以检索与 deviceId 关联的标签。

得到这些信息有点头疼。