首页 > 建站教程 > CSS3+HTML5 >  js调用摄像头报错:Failed to execute 'createObjectURL' on 'URL'正文

js调用摄像头报错:Failed to execute 'createObjectURL' on 'URL'

在学习webRTC时,写了下面一段代码:
function hasUserMedia(){
    return !!(navigator.getUserMedia || navigator.webkitGetUserMedia);
}

if(hasUserMedia){
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
    navigator.getUserMedia({
        video: true,
        audio: true
    }, function(stream){
        var video = document.querySelector('video');
        video.src = window.URL.createObjectURL(stream);
    }, function(err){
        console.log(err)
    })
}
运行时报错了:Failed to execute 'createObjectURL' on 'URL'

原因是Chrome升级后,新版本的Chrome不再支持该用法。其他主流浏览器也是如此,所以原先的代码:
video.src = window.URL.createObjectURL(stream);
需要被修改为
video.srcObject = stream;
一个兼容的写法如下:
try {
     this.srcObject = stream;
} catch (error) {
     this.src = window.URL.createObjectURL(stream);
}
最终修改代码如下,顺利解决:
if(hasUserMedia){
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
    navigator.getUserMedia({
        video: true,
        audio: true
    }, function(stream){
        var video = document.querySelector('video');
        video.srcObject = stream;
    }, function(err){
        console.log(err)
    })
}