MediaRecorder - How to play chunk/blob of video while recording?

半腔热情 提交于 2019-12-05 06:19:36

This is the simplest example I could come up with.

You need a video element for playing the video as you stream it, and a record button to kick off the recording.

The script does the following

  1. Checks for support
  2. Creates success and error handlers for when permission is granted / denied
  3. Ask permission to record
  4. If permitted, calls onSuccess
  5. Creates the recorder
  6. Creates an onclick handler for the record button
  7. If record is clicked, the onclick handler is called
  8. The mediaRecorder starts recording
  9. The video element is set to use the stream
  10. The video element is set to autoplay so the stream shows immediately

HTML

<video id="player"></video>
<button class="record">Record</button>

JS

<script>
  const video = document.querySelector('#player');
  const record = document.querySelector('.record');

  (function start() {
    // 1. check for support
    if (! navigator.mediaDevices.getUserMedia) {
      return console.log('getUserMedia not supported on your browser!');
    }

    // 2. create onSuccess handler
    // 4. called if permitted
    const onSuccess = function (stream) {
      // 5. create the recorder
      const mediaRecorder = new MediaRecorder(stream);

      // 6. create onclick handler for record button
      // 7. called if record is clicked
      record.onclick = function() {
        // 8. starts recording
        mediaRecorder.start();
        // 9. sets video element to use the stream
        video.srcObject = stream;
        // 10. sets the video element to autoplay, otherwise user would have to click play
        video.autoplay = true;
      };
    };

    // 2. create onError handler
    const onError = function (error) {
      console.error('The following error occured: ' + error);
    };

    // 3. ask permission to record audio and video
    const constraints = {video: true, audio: true};
    navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
  })();
</script>

you have to use RequestData for ondataavailable to fire

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