Pause the stream returned by getUserMedia

后端 未结 2 1124
礼貌的吻别
礼貌的吻别 2021-01-16 06:21

I have channelled the stream returned by getUserMedia to element in html page, video now can be seen in that element. The problem is that if I pau

2条回答
  •  被撕碎了的回忆
    2021-01-16 06:43

    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();
        }
    
      });

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

提交回复
热议问题