Samuel Marks
Samuel Marks

Reputation: 1894

MediaStream camera and mic labels before permission given?

It's trivial to get this kind of code to work:

const videoTracks = this.localStream.getVideoTracks();
const audioTracks = this.localStream.getAudioTracks();
if (videoTracks.length > 0)
  this.trace('Using video device: ' + videoTracks[0].label);
if (audioTracks.length > 0)
  this.trace('Using audio device: ' + audioTracks[0].label);

How about before the devices are chosen?

  navigator.mediaDevices
    .enumerateDevices()
    .then(this.gotDevices.bind(this))
    .catch(this.alertsService.add.bind(this.alertsService));
}

gotDevices(deviceInfos: MediaDeviceInfo[]) {
    this.mediaDeviceInfos = deviceInfos;
    this.mediaDeviceInfos.forEach(device => {
        if (device.kind === 'audioinput')
          this.mics.push(device);
        else if (device.kind === 'videoinput')
          this.cams.push(device);
        else
          console.warn(`Unexpected: ${JSON.stringify(device)}`);
    });
}

this.mediaDeviceInfos.some(dev => dev.label) is false. So I have to use dev.deviceId in my input, which is ugly:

camera choice screen

I need the specific device chosen here because I use it like so, to support multiple cams and mics:

const constraints: MediaStreamConstraints = {
  audio: { advanced: [{ deviceId: mic.deviceId, groupId: mic.groupId }] },
  video: { advanced: [{ deviceId: cam.deviceId, groupId: cam.groupId }] }
};

How do I get labels for my camera and mic, so they user can choose them in theme?

Upvotes: 1

Views: 3145

Answers (1)

guest271314
guest271314

Reputation: 1

You can call navigator.mediaDevices.enumerateDevices() within .then() chained to navigator.mediaDevices.getUserMedia(). When protocol is https: and permission is granted to the device or devices the MediaDeviceInfo object "label" property should be set to the available media device.

navigator.mediaDevices.getUserMedia(/* {video:true, audio:true} */)
.then(stream => 
    navigator.mediaDevices
    .enumerateDevices()
    .then(devices => {
      return devices
    })
    .catch(err => {throw err})
)
.then(devices => {
  console.log(devices);
  for (const mediaDeviceInfo of devices) {
    const {deviceId, kind, label} = mediaDeviceInfo;
      console.log(deviceId, kind, label);
  }
})
.catch(err => console.error(err))

Upvotes: 2

Related Questions