我想知道用户的设备是否连接了摄像头和麦克风,如果有,是否允许使用Javascript获取音频和视频流。我想让这个检查至少在Chrome和Firefox上进行。对此有什么一致的API?
发布于 2017-03-02 19:43:32
是的,在授予权限后,检测麦克风和摄像头是否可用是很有可能的。
使用旧的API:
navigator.getUserMedia({ audio: true, video: true}, function (stream) {
if (stream.getVideoTracks().length > 0 && stream.getAudioTracks().length > 0) {
//code for when none of the devices are available
} else {
// code for when both devices are available
}
}, function (error) {
// code for when there is an error
});
使用更新的、基于promise的API:
navigator.mediaDevices.getUserMedia({ audio: true, video: true})
.then(function (stream) {
if (stream.getVideoTracks().length > 0 && stream.getAudioTracks().length > 0){
//code for when none of the devices are available
} else {
// code for when both devices are available
}
})
.catch(function (error) {
// code for when there is an error
});
发布于 2018-06-10 03:52:58
1)您应该使用Media Recorder并了解promise
2)检查浏览器是否支持enumerateDevices接口
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
console.log("This browser does not support the API yet");
}
3)检查用户是否连接了音频和摄像头,只有"videoinput“、"audioinput”或"audiooutput“DeviceInfo.kind
let checking=["audioinput","videoinput"];
let onlyHas=[];
navigator.mediaDevices.enumerateDevices()
.then((devices)=> {
let haveAllDevices=true;
devices.forEach((device)=>{
onlyHas.push(device.kind);
if(!(device.kind==checking[0] || device.kind==checking[1])){
haveAllDevices=false;
}
});
//do something about ...
})
.catch(function(err) {
console.log(err.name + ": " + err.message);
});
4)权限被重用,这意味着如果用户已经拒绝了权限,那么当你调用getUserMedia时,bowser将不会提示任何东西,并将拒绝promise promise抛出一个DOMException类型的错误,否则它将解析promise。当promise拒绝时,可能有许多原因read,其中之一是当用户拒绝访问时,当发生这种情况时,它将抛出类型为NotAllowedError
的DOMException,因此目前我们只对此错误感兴趣。
如果你阅读DOMException,你可以看到你可以访问DOMException.name
,这是你应该被比较的,所以:
let constraints={audio:true,video:true};
navigator.mediaDevices.getUserMedia(constraints)
.then((stream)=>{.....})
.catch((err)=>
{if(err.name=="NotAllowedError"){console.log("User has denied accessed")}
});
PS:关于跨浏览器兼容性目前只支持chrome和MediaRecorder,而IE和IOS不支持https://caniuse.com/#search=MediaRecorder
发布于 2015-05-07 20:22:36
您可以使用表示媒体流的MediaStreamTrack,然后可以使用它的getSources方法,如下所示:html5rocks
如果你没有得到任何媒体资源,那么你的客户就没有网络摄像头。firefox不支持它。
https://stackoverflow.com/questions/30047056
复制相似问题