Pause the stream returned by getUserMedia

此生再无相见时 提交于 2019-12-02 12:30:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!