头图
When developing live web applications, it is often necessary to check whether the camera and microphone are normal before the broadcast. This article introduces how the browser obtains the list of available camera and microphone devices.

media interface

  • mediaDevices.getUserMedia()
  • mediaDevices.enumerateDevices()

The above two media interfaces need to be used, getUserMedia() is used to obtain user authorization, and enumerateDevices() is used to obtain the list of available devices.

Code

 async function openUserMedia(e) {
  // 1. 获取到设备授权
  await navigator.mediaDevices.getUserMedia({video: true, audio: true});

  // 2. 获取设备列表
  navigator.mediaDevices.enumerateDevices()
  .then(function(devices) {
      devices.forEach(function(device) {
          console.log(device.kind + ": " + device.label + " id = " + device.deviceId);
      });
  })
  .catch(function(err) {
      console.log(err.name + ": " + err.message);
  });
}

openUserMedia()

If one or more MediaStreams are active or have persistent authorization, output similar to the following:

 audioinput: 默认 - MacBook Air麦克风 (Built-in) id = default
audioinput: MacBook Air麦克风 (Built-in) id = 343f8207e0b9ebc3f9a98cde134d2818e64b2141b3bd087c58974c727bdca8c0
videoinput: FaceTime HD Camera id = 5ce24d4798ba56b830bc8adc4bcc7171dbe0fcca481f739606190492b21a1e21
videoinput: OBS Virtual Camera (m-de:vice) id = 495bd88129048451bf9b0c5c9342f298c55fdaedf91b3cfe0470a4cbc36e4d26
audiooutput: 默认 - MacBook Air扬声器 (Built-in) id = default
audiooutput: MSI PAG271P (HDMI) id = c20fbe0e2317c5f754d7e334acfeee6b39e7cd64fd37a3ed536142a7ec64f296
audiooutput: MacBook Air扬声器 (Built-in) id = cea14bbd0ab3b96fd22d84941c63aac1c6de60646744efa2d5bd20fa566b7600

You can see that there are audio input, audio output, and video input devices.

We generally need users to choose audio input and video input devices. We can write two filtering methods to display the obtained devices on the page.

Get the camera and microphone separately

 function getCameras() {
    return new Promise((resolve, reject) => {
        navigator.mediaDevices.enumerateDevices()
        .then(function(devices) {
            resolve(devices.filter(d => d.kind === 'videoinput'))
        })
        .catch(function(err) {
            console.log(err.name + ": " + err.message);
        });
    })
}

function getMicrophones() {
    return new Promise((resolve, reject) => {
        navigator.mediaDevices.enumerateDevices()
        .then(function(devices) {
            resolve(devices.filter(d => d.kind === 'audioinput'))
        })
        .catch(function(err) {
            console.log(err.name + ": " + err.message);
        });
    })
}

// 3. 设备列表插入到页面
let cameraSelect = document.getElementById('camera-select');
let microphoneSelect = document.getElementById('microphone-select');

const updateDevice = async () => {
  cameras = await getCameras();
  cameras?.forEach(camera => {
    const option = document.createElement('option');
    option.value = camera.deviceId;
    option.text = camera.label;
    cameraSelect.appendChild(option);
  });

  microphones = await getMicrophones();
  microphones?.forEach(microphone => {
    const option = document.createElement('option');
    option.value = microphone.deviceId;
    option.text = microphone.label;
    microphoneSelect.appendChild(option);
  });
}
updateDevice();

You need to prepare two drop-down boxes on the page:

 <div class='select-wrapper'>
    <div class='input-group mb-3'>
      <label class='input-group-text' for='camera-select'>Camera</label>
      <select class='form-select' id='camera-select'>
      </select>
    </div>
    <div class='input-group mb-3'>
      <label class='input-group-text' for='microphone-select'>Microphone</label>
      <select class='form-select' id='microphone-select'>
      </select>
    </div>
</div>

设备列表

In this way, the devices available in the system are displayed, which is convenient for users to choose.

The article was first published on IICCOM-Personal Blog | Technical Blog "Browser Obtains Camera and Microphone Devices"


来了老弟
508 声望31 粉丝

纸上得来终觉浅,绝知此事要躬行


引用和评论

0 条评论