The WebRTC web page opens the camera and records the video

Ahead, we can Turn on the local camera And see the preview image of the camera on the web page. In this article, we use MediaRecorder to record video. Play the recorded video on the web page and provide download function.

html#

First, create an html interface and put some elements on it

    <video id="v1" playsinline autoplay muted></video>
    <video id="v2" playsinline loop></video>

    <div>
        <button id="startCamera">Turn on the camera</button>
        <button id="stopCamera">Stop the camera</button>
        <button id="record" disabled>Recording</button>
        <button id="play" disabled>play</button>
        <button id="download" disabled>Download Video</button>
    </div>
    <div> Video format used for recording: <select id="codecSelect" disabled></select> </div>
    <div>
        <h4>Video settings</h4>
        <p>Echo cancellation: <input type="checkbox" id="echoCancellation"></p>
    </div>
    <div> <span id="msg" style="font-size:smaller"></span> </div>

    <!-- Use local adapter -->
    <script src="../js/adapter-latest.js" async></script>
  • video
    • v1 for preview
    • v2 is used to play recorded videos
  • button controls the camera to start, record, download and so on
  • Select to select the video format for recording
  • input select echo cancellation

js#

prepare #

Get the elements on the interface first

'use strict';

let mediaRecorder;
let recordedBlobs; // Recorded content
let isRecording = false;

// Get the page elements first
const startCameraBtn = document.querySelector('button#startCamera'); //  Activate camera button
const stopCameraBtn = document.querySelector('button#stopCamera');
const recordBtn = document.querySelector('button#record'); //  Start recording button
const playBtn = document.querySelector('button#play');     //  Play button
const downloadBtn = document.querySelector('button#download'); //  Download video button
const codecSelector = document.querySelector('#codecSelect'); //  Select Format
const msgEle = document.querySelector('span#msg');         //  display messages
const previewV1 = document.querySelector('video#v1'); //  For preview
const recordedV2 = document.querySelector('video#v2');  //  Used to play recorded videos

Video supported formats #

First book several possible formats, and then judge whether they are supported one by one. Found supported formats.

function getSupportedMimeTypes() {
  const possibleTypes = [
    'video/webm;codecs=vp9,opus',
    'video/webm;codecs=vp8,opus',
    'video/webm;codecs=h264,opus',
    'video/mp4;codecs=h264,aac',
  ];
  return possibleTypes.filter(mimeType => {
    return MediaRecorder.isTypeSupported(mimeType);
  });
}

Turn on the camera #

Also use the getUserMedia method. The width and height of the video are specified here. Echo cancellation is optional.

// Activate the camera
startCameraBtn.addEventListener('click', async () => {
  startCameraBtn.disabled = true;
  const isEchoCancellation = document.querySelector('#echoCancellation').checked;
  const constraints = {
    audio: {
      echoCancellation: { exact: isEchoCancellation }
    },
    video: {
      width: 1280, height: 720
    }
  };
  await init(constraints);
});

async function init(constraints) {
  try {
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    gotStream(stream);
  } catch (e) {
    showMsg(`navigator.getUserMedia error:${e.toString()}`);
  }
}

function gotStream(stream) {
  recordBtn.disabled = false;
  showMsg('Got it stream:', stream);
  window.stream = stream;
  previewV1.srcObject = stream;

  // Reset
  var codecOption = codecSelector.lastChild;
  while (codecOption != null) {
    codecSelector.removeChild(codecOption);
    codecOption = codecSelector.lastChild;
  }

  getSupportedMimeTypes().forEach(mimeType => {
    const option = document.createElement('option');
    option.value = mimeType;
    option.innerText = option.value;
    codecSelector.appendChild(option);
  });
  codecSelector.disabled = false; // You can choose
}

Here's how to stop the camera

stopCameraBtn.addEventListener('click', () => {
  var stream = previewV1.srcObject;
  if (stream == null) {
    return;
  }
  const tracks = stream.getTracks();
  tracks.forEach(function (track) {
    track.stop();
  });
  previewV1.srcObject = null;
  window.stream = null;
  codecSelector.disabled = true;
  startCameraBtn.disabled = false;
});

start recording #

Start recording video

function startRecording() {
  recordedBlobs = [];
  const mimeType = codecSelector.options[codecSelector.selectedIndex].value;
  const options = { mimeType };

  try {
    mediaRecorder = new MediaRecorder(window.stream, options);
  } catch (e) {
    showMsg(`establish MediaRecorder error: ${JSON.stringify(e)}`);
    return;
  }

  showMsg('establish MediaRecorder', mediaRecorder, ' -> options', options);
  recordBtn.textContent = 'Stop recording';
  isRecording = true;
  playBtn.disabled = true;
  downloadBtn.disabled = true;
  codecSelector.disabled = true;
  mediaRecorder.onstop = (event) => {
    showMsg('Recording stopped: ' + event);
    showMsg('Recorded data Blobs: ' + recordedBlobs);
  };
  mediaRecorder.ondataavailable = handleDataAvailable;
  mediaRecorder.start();
  showMsg('Recording starts mediaRecorder: ' + mediaRecorder);
}

function handleDataAvailable(event) {
  if (event.data && event.data.size > 0) {
    recordedBlobs.push(event.data);
  }
}

recordBtn.addEventListener('click', () => {
  if (isRecording == false) {
    startRecording();
  } else {
    stopRecording();
    recordBtn.textContent = 'start recording ';
    playBtn.disabled = false;
    downloadBtn.disabled = false;
    codecSelector.disabled = false;
  }
});
  • Reset recordedBlobs = []
  • Get the selected video format mimeType
  • Create a new MediaRecorder object and pass in the previously obtained stream
  • Process the status of each button (ui)
  • mediaRecorder
    • Set stop listener onstop
    • Monitor the recorded data ondatavailable, and store it in the recordedBlobs when there is data
    • Start the recording mediarecorder start()

Stop recording #

function stopRecording() {
  mediaRecorder.stop();
}

Play the recorded video #

The recorded video content is stored in recordedBlobs. Create a new Blob and give it to video (recordedV2) to play

playBtn.addEventListener('click', () => {
  const mimeType = codecSelector.options[codecSelector.selectedIndex].value.split(';', 1)[0];
  const superBuffer = new Blob(recordedBlobs, { type: mimeType });
  recordedV2.src = null;
  recordedV2.srcObject = null;
  recordedV2.src = window.URL.createObjectURL(superBuffer);
  recordedV2.controls = true;
  recordedV2.play();
});

Download Video #

The recorded video content is stored in recordedBlobs.

downloadBtn.addEventListener('click', () => {
  const blob = new Blob(recordedBlobs, { type: 'video/webm' });
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = url;
  a.download = 'video_' + new Date().getTime() + '.webm';
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  }, 100);
});

Create a new blob and an a element. Create an ObjectURL according to the blob and pass it to the href of the a element. Modify the default name of the downloaded file a.download. Trigger the click() of the a element to let the browser download the file.

Delay removing this a.

Summary #

getUserMedia() starts the video and gets the video stream. MediaRecorder records video. Use Blob to play and download. Achieve a small recorded video effect. Video data is cached in the object.

For complete effect, please refer to video recording

Original link

Author: AnRFDev

source: https://www.cnblogs.com/rustfisher/p/15637449.html

Copyright: this work adopts Signature - non commercial use - share 4.0 international in the same way License under the license agreement.

Added by rbama on Sun, 27 Feb 2022 03:53:49 +0200