WebRTC API获取音视频设备

一. enumerateDevices

        WebRTC 提供了 mediaDevices.enumerateDevices API 来获取系统的音视频设备。

var ePromise = navigator.mediaDevices.enumerateDevices();

        上述调用返回值是一个 Promise 对象,当完成时会接收一个 MediaDeviceInfo 对象的数组,MediaDeviceInfo 属性值含义解释如下。

属性 含义
deviceId 设备 ID
label 设备名称
kind 设备种类,如 audioinput/videoinput/audiooutput/videooutput
groupId 设备组 ID

二. 实例演示

<!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);
}

        运行后效果如下所示,可以看到所有的音频输入设备,视频输入设备,音频输出设备。

猜你喜欢

转载自blog.csdn.net/weixin_38102771/article/details/123611980