Pause the stream returned by getUserMedia

2020-05-03 07:31发布

I have channelled the stream returned by getUserMedia to <video> element in html page, video now can be seen in that element. The problem is that if I pause the video from the controls of video element, and then resume after x seconds, then the timer being shown in video element will jump to pauseTime + x seconds. I guess this is because the stream is not getting paused as we pause the playback in video element. If so can we pause the stream too.

1条回答
时光不老,我们不散
2楼-- · 2020-05-03 07:49

That is the very thing of Streams, you can't pause them...

But what you can do however, is to buffer this stream, and play what you've bufferred.

To achieve this with a MediaStream, you can make use of the MediaRecorder API, along with the MediaSource API.

But note that now, you'll obviously get more delay than when you were reading the stream directly.

navigator.mediaDevices.getUserMedia({
    video: true
  })
  .then(stream => {
    const mediaSource = new MediaSource();
    let data, sourceBuffer;
    vid.src = URL.createObjectURL(mediaSource);
    mediaSource.addEventListener('sourceopen', sourceOpen);

    const recorder = new MediaRecorder(stream, {
      mimeType: 'video/webm; codecs="vp8"'
    });
    const chunks = [];
    recorder.ondataavailable = e => push(e.data);

    function push(data) {
      if (mediaSource.readyState !== "open") return;
      let fr = new FileReader();
      fr.onload = e => sourceBuffer.appendBuffer(fr.result);
      fr.readAsArrayBuffer(new Blob([data]));
    }

    function sourceOpen(_) {
      recorder.start(50);
      sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp8"');
      vid.play();
    }

  });
<video id="vid" controls></video>

And as a fiddle since StackSnippets are not very gUM friendly.

查看更多
登录 后发表回答