搭建环境环境见拙作:
https://blog.youkuaiyun.com/Crisf/article/details/113242541
本次记录navigator.mediaDevices.enumerateDevices() 返回的label,deviceId为空的解决办法。问题截图如下:
代码如下所示:
结构如下:
index.html:
<html>
<head>
<title> WebRTC get audio and video devices </title>
</head>
<body>
<div>
<label>audio input device:</label>
<select id="audioSource"></select>
</div>
<div>
<label>audio output device:</label>
<select id="audioOutput"></select>
</div>
<div>
<label>video input device:</label>
<select id="videoSource"></select>
</div>
<script src = "./js/client.js"></script>
</body>
</html>
client.js:
'use strict'
var audioSource = document.querySelector("select#audioSource");
var audioOutput = document.querySelector("select#audioOutput");
var vedioSource = document.querySelector("select#videoSource");
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(deviceInfo){
console.log(deviceInfo.kind + ": label = "
+ deviceInfo.label + ": id = "
+ deviceInfo.deviceId + ": groupId = "
+ deviceInfo.groupId);
var option = document.createElement('option');
option.text = deviceInfo.label;
option.value = deviceInfo.deviceId;
if(deviceInfo.kind === 'audioinput'){
audioSource.appendChild(option);
}else if(deviceInfo.kind === 'audiooutput'){
audioOutput.appendChild(option);
}else if(deviceInfo.kind === 'videoinput'){
videoSource.appendChild(option);
}
});
}
function handleError(err){
console.log(err.name + " : " + err.message);
}
问题原因:
浏览器出于安全考虑,只对信任的域名开放核心功能的调用。要解决这个问题,先要看看浏览器是否信任该域名。打开浏览器的”设置“的页面并搜索“摄像头”及“麦克风”的选项
没有在允许访问摄像头的范围之内,因此权限不足,label属性不可见。当然,此处也不能手动添加信任网址。
解决办法:
解决的办法就是让程序来“调用”摄像头,引导浏览器弹出询问框,我们再做允许的操作。
在 navigator.mediaDevices.enumerateDevices() 方法前加上以下代码:
navigator.mediaDevices.getUserMedia({audio: true, video: true});
再次发布后,访问会出现询问弹窗
允许之后,重新访问到根路径,这里是https://chrisf.work.chrisf.work,再点“device”,再点“index.html”,即可获取到label
这是再次打开浏览器的“设置”--“麦克风”/“摄像头”,可以看到 我们的域名已经添加到允许中
此时,即使删除掉刚才添加的代码,依然能获取到label,是因为本地浏览器已经信任该域名的访问请求,在浏览器设置中,把允许中的域名都删掉(不能只删除一个,要把摄像头和麦克风的都删掉),再次测试,则不能获取label,因此证明问题出在此处。