1. What is MediaRecorder

MediaRecorder is a powerful and simple API provided by browsers. Specifically for audio and video recording. Using the MediaRecorder constructor, create an instance object to record the specified MediaStream object. For details, see MediaRecorder.

2. What can be recorded?

You can record any media form tag, such as

The encoding process of media data streams is implemented by the browser and therefore depends on the capabilities of the browser. Chrome and Firefox support well. The mobile terminal is compatible with the Chrome kernel browser built into Android. Ios and Internet Explorer are not supported.

3. MediaRecorder method API

methods describe
var recorder = MediaRecorder()) Constructor: Creates a new MediaRecorder object to record data during recording operations
recorder.start(timeslice) Start recording: record media to a Blob object, timeslice: interval at which data is returned at the same time. recorder.state = recording
recorder.pause() Recording pause: The current data collection is retained for later use. recorder.state = paused
recorder.resume() Resume recording: Continue to collect data to Blob, recorder. State = recording
recorder.requestData() Receive data: Raises a DataAvailable event that returns data as captured media and creates a Blob object to put the data into
recorder.stop() Stop recording: Raises the dataAvailable event (which collects data into the Blob), triggering the stop event. recorder.state = inactive
MediaRecorder.isTypeSupported(mimeType) Determine the browser coding capabilities of the API, browser support.

4. MediaRecorder events and attributes

The event describe
recorder.onstart = () =>() Triggered when the start() method is called
recorder.onpause = () =>() Triggered when the pause() method is called
recorder.onresume = () =>() Triggered when the resume() method is called
recorder.onstop = () =>() Triggered when the stop() method is called
recorder.onerror = () =>() Triggered when an exception occurs during recording
recorder.ondataavailable Called when the dataAvailable event is fired. Dataavailable Triggered when the MediaRcorder passes media data to the program.
recorder.state The state of recording: inactive (not started or stopped),recording(in progress), paused (paused)
recorder.stream Read-only, returns the flow passed to the MediaRecorder constructor when MediaRecorder is created
recorder.mimeType Read-only: MIME type, used to describe the format of the recorded media
ignoreMutedMedia The input source used to specify whether MediaRecorder records a silent input source. If false, silent audio or black screen video will be recorded. The default value is false
videoBitsPerSecond Returns the encoding rate used for the video
audioBitsPerSecond Returns the encoding rate used for audio

Ondataavailable a:

  • If the media stream ends, media data not delivered to OnDataAvailable will be delivered in a single Blob.
  • When the stop method is called, all media data since the beginning of recording or the last DataAvailable event is passed into the Blob and ends.
  • RequestData () calls: all recorded the development or the last | dataavailable events since the incident all media will be passed, and then love you create a new Blob, media capture to continue into the new Blob.
  • Start (timeslice) If there is a timeslice, everytimesliceA DataAvailable event is emitted.

5. Recording process analysis

  • 1. Set MediaStream or HTMLMediaElement(such as audio or video) as the source of media data
  • 2. Create the MediaRecorder object to specify the media resource stream and any other required options, such as MIME
  • 3. Set onDataAvailable as a handler for dataAvailable events, which will be called whenever data is received
  • 4. After the media source data is ready, call start() to start recording
  • 5. The Dataavailable event handler is called whenever there is data. This event has a data attribute that values the media data contained in the Blob
  • 6. Recording stops automatically when the source media stops playing, and can be stopped at any time by calling the stop recording method stop().

Tips: A single Blob of recorded multiple media segments does not necessarily play on its own; the media needs to be reassembled before playback.

6. Record using HTML media elements

Now, we read the video stream from the camera to record and download it. Let’s see what it looks like.



Follow the recording process analyzed above. The HTML DOM is as follows:

<div class="left">
  <div id="startButton" class="button">Start</div>
  <h2>Preview</h2>
  <div class="video"><video id="preview" width="100%" height="auto" autoplay muted></video></div>
</div>

<div class="right">
  <div class="rightBtn">
    <div id="stopButton" class="button">Stop</div>
    <a id="downloadButton" class="button">Download</a>
  </div>
  <h2>Recording</h2>
  
  <div class="video"><video id="recording" width="160" height="120" controls></video></div>
</div>
Copy the code

Related JS are as follows:

let preview = document.getElementById("preview");
let recording = document.getElementById("recording");
let startButton = document.getElementById("startButton");
let stopButton = document.getElementById("stopButton");
let downloadButton = document.getElementById("downloadButton");
let dataChunks = [];
let recorder;

// Start recording
function startRecording(stream, lengthInMS) {
  recorder = new MediaRecorder(stream);

  recorder.ondataavailable = (event) = > {
    let data = event.data;
    dataChunks.push(data);
  };
  recorder.start(1000);
  console.log(recorder.state + " start to recording .....");
}

stopButton.addEventListener("click".() = > {
  // close the recording
  preview.srcObject.getTracks().forEach((track) = > track.stop());
  recorder.stop();

  // Play recorded video
  let recordedBlob = new Blob(dataChunks, { type: "video/webm" });
  recording.src = URL.createObjectURL(recordedBlob);

  // Save download video, click the download button, you can download it
  downloadButton.href = recording.src;
  downloadButton.download = "RecordedVideo.webm";
});

startButton.addEventListener("click".() = > {
  // get the stream
  navigator.mediaDevices
    .getUserMedia({
      audio: true.video: true,
    })
    .then((stream) = > {
      // set the stream to left video
      preview.srcObject = stream;
      // set the stream to <a> for download
      downloadButton.href = stream;
      // captureStream: which is streaming a real-time capture of the content being rendered in the media element. 
      // A MediaStream object which can be used as a source for audio or video data by other media
      preview.captureStream =
        preview.captureStream || preview.mozCaptureStream;
      startRecording(preview.captureStream());
    })
    .catch((err) = > {
      console.log("recording error: ", err);
    });
});
Copy the code