且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MediaRecorder-如何在录制时播放视频块/视频?

更新时间:2023-10-29 18:35:46

这是我能想到的最简单的示例.

This is the simplest example I could come up with.

在流式播放视频时,您需要一个video元素,并需要一个录制按钮来开始录制.

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

脚本执行以下操作

  1. 检查支持情况
  2. 在授予/拒绝权限时创建成功和错误处理程序
  3. 询问录制权限
  4. 如果允许,请调用onSuccess
  5. 创建记录器
  6. 为记录按钮创建一个onclick处理程序
  7. 如果单击记录,则将调用onclick处理程序
  8. mediaRecorder开始记录
  9. 视频元素设置为使用流
  10. 视频元素设置为自动播放,因此视频流立即显示
  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>