gpt4 book ai didi

javascript - 使用 getUserMedia 访问设备摄像头

转载 作者:行者123 更新时间:2023-12-03 05:47:01 25 4
gpt4 key购买 nike

下面的代码一直成功工作,直到我添加了一些额外的代码,因为我试图让用户知道他们的相机是否准备好/可用。我的 html 如下所示:

<div id="notes">
</div>
<div id="video-container">
<video id="camera-stream" width="500" autoplay></video>
</div>

这里是 .js

<script type="text/javascript">
window.onload = function() {
var statusHTML = '<ul>';
navigator.getUserMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
if (navigator.getUserMedia) {
navigator.getUserMedia(
{
video: true,
audio: true
},
function(localMediaStream) {
statusHTML += '<li>You have a camera!</li>';
var vid = document.getElementById('camera-stream');
vid.src = window.URL.createObjectURL(localMediaStream);
},
function(err) {
statusHTML += '<li>You dont have a camera!</li>';
console.log('The following error occurred when trying to use getUserMedia: ' + err);
}
);
statusHTML += '</ul>';
document.getElementById('notes').innerHTML = statusHTML;
} else {
alert('Sorry, your browser does not support getUserMedia');
}
}
</script>

我添加了这 4 个不起作用的代码,我不确定我做得是否正确:

  var statusHTML = '<ul>';
statusHTML += '<li>You have a camera!</li>';
statusHTML += '<li>You dont have a camera!</li>';
statusHTML += '</ul>';
document.getElementById('notes').innerHTML = statusHTML;

总而言之,我试图在用户加载页面后立即向页面打印一条消息,它应该表明他们是否有可用的相机。任何帮助将不胜感激。

最佳答案

尝试直接更改innerHTML,而不是在使用变量的函数之后。我尝试了一下,效果很好:

window.onload = function() {
navigator.getUserMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
if (navigator.getUserMedia) {
navigator.getUserMedia(
{
video: true,
audio: true
},
function(localMediaStream) {
document.getElementById('notes').innerHTML = '<ul><li>You have a camera!</li></ul>';
var vid = document.getElementById('camera-stream');
vid.src = window.URL.createObjectURL(localMediaStream);
},
function(err) {
document.getElementById('notes').innerHTML = '<ul><li>You dont have a camera!</li></ul>';
alert('The following error occurred when trying to use getUserMedia: ' + err);
}
);
} else {
alert('Sorry, your browser does not support getUserMedia');
}
}

关于javascript - 使用 getUserMedia 访问设备摄像头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40300349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com