WebRtc05: 设备管理

获取音视频设备

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);
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值