WebRtc05: 设备管理

发布于:2025-02-10 ⋅ 阅读:(75) ⋅ 点赞:(0)

获取音视频设备

enumerateDevices

基本格式

var ePromise = navigator.mediaDevices.enumerateDevices();

MediaDevicesInfo

属性:
deviceID 设备ID
label 设备的名字
kind 设备的种类
groupID 两个设备groupID相同,说明是同一个物理设备

Promise

用于处理异步操作的对象,表示一个异步操作的最终完成(或失败)及其结果值
在这里插入图片描述
先处理handle,然后成功则执行resolve,否则执行reject

例子

在这里插入图片描述index.html

<html>
    <head>
        <title> WEBRTC get audio and viedo devices</title>
    </head>
    <body>
        <script src="./js/client.js"></script>
    </body>
</html>

client.js

'use strict'
if (!navigator.mediaDevices 
    || !navigator.mediaDevices.enumerateDevices) {
        console.log('enumerateDevices is not supported');
} else {
    navigator.mediaDevices.enumerateDevices()
        .then(gotDevices)
        .catch(handleError);
}
function gotDevices(deviceInfos) {
    deviceInfos.forEach(function(deviceInfos) {
        console.log(deviceInfos.kind + ": label= "
            + deviceInfos.label + ": id= "
            + deviceInfos.deviceId + ": groupId= "
            + deviceInfos.groupId
        );
    });
}
function handleError(err) {
    console.log(err.name + " : " + err.message);
}

实测没有使用https时,navigator.mediaDevices没有生效,直接打印enumerateDevices is not supported,为了使用https,需要备案网站,而备案又会审核很久,所以最好尽快备案

上述代码中没有请求访问设备的权限,所以默认会获取不到,需要先请求在打印

'use strict';

function listDevices() {
    navigator.mediaDevices.enumerateDevices()
        .then(gotDevices)
        .catch(handleError);
}

function gotDevices(deviceInfos) {
    deviceInfos.forEach(deviceInfo => {
        console.log(`${deviceInfo.kind}: label=${deviceInfo.label || 'N/A'}: id=${deviceInfo.deviceId}: groupId=${deviceInfo.groupId}`);
    });
}

function handleError(err) {
    console.error(err.name + ": " + err.message);
}

if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
    console.log('enumerateDevices is not supported.');
} else {
    // 请求权限后再列出设备
    navigator.mediaDevices.getUserMedia({ audio: true, video: true })
        .then((stream) => {
            listDevices();
            stream.getTracks().forEach(track => track.stop());
        })
        .catch(handleError);
}

网站公告

今日签到

点亮在社区的每一天
去签到