WebRTC API to get audio and video devices

一. enumerateDevices

        WebRTC provides mediaDevices.enumerateDevices API to get the audio and video devices of the system.

var ePromise = navigator.mediaDevices.enumerateDevices();

        The return value of the above call is a Promise object. When it is completed, it will receive an array of MediaDeviceInfo objects. The meaning of the MediaDeviceInfo attribute value is explained as follows.

Attributes meaning
deviceId device ID
label device name
kind Device type, such as audioinput/videoinput/audiooutput/videooutput
groupId device group ID

2. Example demonstration

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>WebRTC获取音视频设备</title>
    </head>
    <body>
        <div>
            <label>音频输入设备</label>
            <select id="audio_input"></select>
        </div>
        <div>
            <label>视频输入设备</label>
            <select id="video_input"></select>
        </div>
        <div>
            <label>音频输出设备</label>
            <select id="audio_output"></select>
        </div>
        <script src="./js/enumerate_devices.js"></script>
    </body>
</html>
'use strict'

var audioInput = document.querySelector("select#audio_input");
var videoInput = document.querySelector("select#video_input");
var audioOutput = document.querySelector("select#audio_output");

function HandleError(err) {
    console.log(err.name + "," + err.message);
}

function GetStream(stream) {
    return navigator.mediaDevices.enumerateDevices();
}

function GetDevices(deviceInfos) {
    deviceInfos.forEach(function(deviceInfo) {
        var option = document.createElement("option");
        option.text = deviceInfo.label;
        option.value = deviceInfo.deviceId;
        if (deviceInfo.kind === "audioinput") {
            audioInput.appendChild(option);
        } else if (deviceInfo.kind === "videoinput") {
            videoInput.appendChild(option);
        } else if (deviceInfo.kind === "audiooutput") {
            audioOutput.appendChild(option);
        } else if (deviceInfo.kind === "videooutput") {
            videoOutput.appendChild(option);
        } else {
            console.log("unknown device kind");
        }
    });
}

if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
    console.log('enumerateDevices is not supported!');
} else {
    navigator.mediaDevices.getUserMedia({audio: true, video: true})
    .then(GetStream)
    .then(GetDevices)
    .catch(HandleError);
}

        The effect after running is as follows, you can see all audio input devices, video input devices, and audio output devices.

Guess you like

Origin blog.csdn.net/weixin_38102771/article/details/123611980