我正在将ZXing JS条码扫描器库https://github.com/zxing-js/library/与视频流输入(网络摄像头或电话摄像头)配合使用,如以下代码所示。
通常,如何在视频流刚刚开始时向<video>
添加事件侦听器以执行操作?(使用MediaDevices.getUserMedia
视频流API的视频是从ZXing的MediaDevices.getUserMedia
开始的)?
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/[email protected]/umd/index.min.js"></script>
<video id="video"></video>
,但是如果出现对话框“您是否允许该网站使用摄像机,设备?”,那么2秒是不够的。事件“ VideoHasJustStarted”上的侦听器会更好。
有几种方法可以使用事件侦听器来检测视频是否正在播放或可以播放:
setTimeout(..., 2000)
最类似于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
以上假设视频标签的API始终应用。如果上述方法不起作用,则可能会发现使用事件https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events是替代方法
started
video.addEventListener('started', function() {
...
})
非常奇怪的是,用于检测任何更改(可能出于安全原因)的事件是https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API#Events:
devicechange
A
navigator.mediaDevices.addEventListener('devicechange', function(e) { ... });
事件被发送到devicechange
实例,只要媒体设备(例如相机,麦克风或扬声器)连接到系统或从系统中卸下。这是通用MediaDevices
,没有添加的属性。
Event