00.webRTC检测音视频设备

转载自https://www.jianshu.com/p/936c6b681022

获取到的音视频设备信息包括:

属性 说明
deviceId 设备ID
label 设备的名字
kind 设备的种类
groupId 设备的groupId,如果2个设备的groupId相同,说明是同一个物理设备
  • html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>webrtc获取音视频设备</title>
        <script type="text/javascript" src="js/jquery-1.12.4.js"></script>
    <script type="text/javascript" src="js/client.js"></script>
</head>
<body>

    <div>
        <label>音频输入设备:</label>
        <select id="audioinput">
        </select>
    </div>
    
    <div>
        <label>音频输出设备:</label>
         <select id="audiooutput">
         </select>
    </div>

    <div>
        <label>视频输入设备:</label>
         <select id="videoinput">
         </select>
    </div>
    
</body>
</html> 
  • client.js
// 这种方式在各个浏览器都可以(不过在Safari和Firefox浏览器获取的设备信息和在Chrome获取的信息还是不一样的)
'use strict'


if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    console.log('不支持获取设备信息!');
}else{
    // 首先获取到流,获取流成功后再获取设备信息
    navigator.mediaDevices.getUserMedia({video:true,audio:true}).then(gotMediaStream).then(gotDevices).catch(handleError);

}

// 采集音视频数据成功时调用的方法
function gotMediaStream(stream){

    return navigator.mediaDevices.enumerateDevices();

}

// 浏览器获取音视频设备成功时调用的方法
function gotDevices(deviceInfos){
    const audioInputSelect = $("#audioinput")[0];
    const audioOutputSelect = $("#audiooutput")[0];
    const videoInputSelect = $("#videoinput")[0];

    deviceInfos.forEach(function(deviceInfo){
        console.log('设备种类='+deviceInfo.kind + ':设备名 = ' + deviceInfo.label + ';设备id = ' + deviceInfo.deviceId + ';groupId='+deviceInfo.groupId);
        
        const option = document.createElement('option');
        option.value = deviceInfo.deviceId;
        option.text = deviceInfo.label;
        if (deviceInfo.kind === 'audioinput') {
            audioInputSelect.appendChild(option);
        }else if (deviceInfo.kind === 'audiooutput') {
            audioOutputSelect.appendChild(option);
        }else if (deviceInfo.kind === 'videoinput') {
            videoInputSelect.appendChild(option);
        }

    })
}

// 浏览器获取音视频设备失败时调用的方法
function handleError(err){
    console.log(err.name+':'+err.message);
}

在vscode里面Open with Live Server打开html:
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容