我想用JS从摄像头上得到一段视频,但没有镜头。
消息:
DOMException:无法启动视频源
App.js
const video = document.getElementById("video");
function startVideo() {
navigator.getUserMedia(
{
video: {}
},
stream => (video.srcObject = stream),
err => console.log(err)
);
}
startVideo();
index.html
...
<body>
<video id="video" width="720" height="540" autoplay muted></video>
</body>
...
谢谢你的帮忙
发布于 2022-08-31 04:21:32
当我试图在移动浏览器上切换相机时,我在某些安卓设备(索尼XA2)上遇到了这个问题,因为我在每个摄像头上反复调用navigator.mediaDevices.getUserMedia
。
我找到的解决方案是确保停止您创建的先前流中的所有轨道。
this.stream.getTracks().forEach(t => {
t.stop();
this.stream.removeTrack(t);
});
如果没有前面的代码,您就无法在某些Android设备上切换摄像机:(演示),(代码)显示的错误是DOMException: Requested device not found
注意:由于安全限制,下面的代码段似乎不会在堆栈溢出时执行,所以请使用jsfiddle链接。
class Camera {
constructor({ video }) {
this.facingMode = "environment";
this.video = video;
video.onloadedmetadata = () => {
video.play();
};
}
async toggleCamera() {
if (this.facingMode === "environment") {
this.facingMode = "user";
} else {
this.facingMode = "environment";
}
try {
if (this.stream){
/* On some android devices, it is necessary to stop the previous track*/
this.stream.getTracks().forEach(t => t.stop());
}
this.stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: this.facingMode,
}
});
} catch (e) {
console.error(e);
}
this.video.srcObject = this.stream;
}
}
const camera = new Camera({
video: document.querySelector("video"),
});
const button = document.querySelector("button");
button.addEventListener('click', () => {
camera.toggleCamera();
});
<button>
Toggle Camera
</button>
<video></video>
https://stackoverflow.com/questions/60837628
复制相似问题