视频流开始时触发的事件,使用 getUserMedia

Event triggered when the video stream is started, with getUserMedia

我正在使用带视频流输入(网络摄像头或 phone 摄像头)的 ZXing JS 条码扫描器库 https://github.com/zxing-js/library/,详见以下代码。

一般来说,如何给<video>添加一个事件监听器,在视频流刚开始的时候做一个动作?(视频使用MediaDevices.getUserMedia视频流API,从ZXing的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) 当用户点击按钮开始播放视频时,但显然在出现对话框 "Do you want to allow this website to use the camera device?" 的情况下这会失败,然后2秒不够。监听事件 "VideoHasJustStarted" 会更好。

编辑:
Here is a jsFiddle 显示问题:无法处理各种事件:starteddevicechange

有几种方法可以使用事件侦听器检测视频是否正在播放或可以播放:

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。但根据您希望如何执行您的功能,上述方法之一应该适合您的需要。

有关视频事件的更多信息:https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events

例子

// 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>

在笔记本电脑上的 Firefox 上测试 - 使用网络摄像头需要许可,并且 console.log 在视频开始时触发。由于 Whosebug 阻止了上述 运行 内联,link to working fiddle