我正在使用ZXing JS条形码扫描器库https://github.com/zxing-js/library/与视频流输入(摄像头或电话摄像头),如下面的代码详细说明。
一般情况下,当视频流刚刚开始时,如何向<video> 添加事件侦听器来执行操作?(使用MediaDevices.getUserMedia视频流API的视频,从中兴的decodeFromInputVideoDevice开始)?
const codeReader = new ZXing.BrowserQRCodeReader();
codeReader
.decodeFromInputVideoDevice(undefined, 'video') // uses the default input
.then(result => console.log(result.text)) // this happens when the barcode is found / recognized
.catch(err => console.error(err));<script src="https://unpkg.com/@zxing/library@0.15.2/umd/index.min.js"></script>
<video id="video"></video>
注意:现在,当用户单击按钮启动视频时,我使用的是setTimeout(..., 2000),但是如果有一个对话框“您想让这个网站使用相机设备吗?”,那么2秒是不够的。事件"VideoHasJustStarted“上的侦听器会更好。
编辑:
这是一个jsFiddle显示了问题:不处理各种事件:started、devicechange。
发布于 2020-02-25 11:07:48
有几种方法可以使用事件侦听器检测视频是否正在播放或可以播放:
let video = document.querySelector('video');
// Video has been started/unpaused
video.addEventListener('play', function() {
...
})
// Video has resumed play/started/unpaused/finished buffering/finished seeking, etc
video.addEventListener('playing', function() {
...
})
// Video can start playing (but might not be playing)
video.addEventListener('canplay', function() {
...
})
// Video can be played without buffering (but might not be playing)
video.addEventListener('canplaythrough', function() {
...
})与VideoHasJustStarted最相似的可能是playing。但是,取决于您想要如何执行您的函数,上述方法之一应该适合您的需要。
更多关于视频事件的信息:事件
示例
// Get video
var video = document.querySelector('video');
// Add event listener to monitor events
video.addEventListener('playing', () => {
console.log('Video is now streaming!')
});
// Add stream
navigator.mediaDevices.getUserMedia({
video: true
})
.then(function(stream) {
var videoTracks = stream.getVideoTracks();
stream.onremovetrack = function() {
console.log('Stream ended');
};
window.stream = stream;
video.srcObject = stream;
})
.catch(function(error) {
console.log(error);
});<video id="video" autoplay muted></video>
在膝上型电脑上的火狐上进行测试--当视频开始时,请求允许使用网络摄像头和console.log。由于StackOverflow阻止了上面的内联运行,所以连接到工作小提琴
https://stackoverflow.com/questions/60290523
复制相似问题