Home  >  Article  >  Web Front-end  >  How to create video and audio recorders using the JavaScript MediaRecorder API?

How to create video and audio recorders using the JavaScript MediaRecorder API?

WBOY
WBOYforward
2023-09-13 23:57:021297browse

如何使用 JavaScript MediaRecorder API 创建视频和音频录制器?

In this tutorial, you will learn how to create audio and video recorders using the JavaScript MediaRecorder API. So this can be done using WebRTC.

What is WebRTC?

WebRTC is the abbreviation of real-time communication. We can access and capture the webcam and microphone devices available in the user's device.

We can access the user device’s webcam and microphone using ECMAScript objects

navigator.mediaDevices.getUserMedia(constraints).

Therefore, the getUserMedia function by default seeks the user's permission to use your webcam. This function returns a promise, once you click OK and agree, the function will be triggered and enable the webcam in your system, otherwise if you don't allow it, then it also A catch method that will turn off the webcam.

We can also pass a parameter to the function getUserMedia() function, which may be like if we want an image of a certain width or height.

Front-end design

Our front-end part will contain the following elements -

For video the recording screen will have some elements like -

  • The video element that will display the video media screen

  • Start button will start video recording

  • The Stop button will stop the video recording stream.

For audiorecording it will have two buttons

  • The start button will start recording

  • The Stop button will stop the audio recording stream.

We will add font Awesome CDN to add start and stop button icons and to make the page more attractive we will add CSS styles on the elements.

HTML code

Example

<!DOCTYPE html>
<html>
<head>
   <title>Video & Audio Recorder</title>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
   <style>
      body {
         text-align: center;
         color: red;
         font-size: 1.2em;
      }
      /* styling of start and stop buttons */
      #video_st, #video_en, #aud_st, #aud_en{
         margin-top: 10px;
         padding: 10px;
         border-radius: 4px;
         cursor: pointer;
      }
      #vidBox{
         background-color: grey;
      }
      /*video box styling*/
      video {
         background-color: gray;
         display: block;
         margin: 6px auto;
         width: 520px;
         height: 240px;
      }
      /*audio box styling*/
      audio {
         display: block;
         margin: 6px auto;
      }
      a {
         color: green;
      }
   </style>
</head>
<body>
   <h1 style="color:blue"> Video-Audio recorder</h1>
   <div class="display-none" id="vid-recorder">
   
   <h3>Record Video </h3>
   <video autoplay id="vidBox"> </video>
   
   <!-- click this button to start video recording -->
   <button type="button" id="video_st" onclick="start_video_Recording()"> <i class="fa fa-play"></i></button>
   
   <!-- click this button to stop video recording -->
   <button type="button" id="video_en" disabled onclick="stop_Recording(this, document.getElementById('video_st'))">
   
   <i class="fa fa-stop"></i>
   </button>
   
</div>
<!-- ------------ -->
<br>
<hr>
<!-- ------------ -->
   <div class="display-none" id="audio_rec">

      <h3> Record Audio</h3>
      <!-- click this button to start audio recording -->
      <button type="button" id="aud_st"
         onclick="start_audio_Recording()"><i class="fa fa-play"></i>
      </button>
      
      <!-- click this button to stop video recording -->
      <button type="button" id="aud_en"disabled onclick="stop_Recording(this, document.getElementById('aud_st'))"> <i class="fa fa-stop"></i></button>
   </div>
</body>
</html>

When you click on the "Start Video" button it will call the start_video_Recording() function and the "Stop" button will call stop_Recording () Something like Specifically, for audio, clicking the start button will trigger the function start_audio_Recording(), and for the stop button, the stop_Recording() function will be called.

start_video_Recording() function

Let's define a function to start the video and record it.

function start_video_Recording() {
   // stores the recorded media
   let chunksArr= [];
   const startBtn=document.getElementById("video_st");
   const endBtn=document.getElementById("video_en");
   
      // permission to access camera and microphone
      navigator.mediaDevices.getUserMedia({audio: true, video: true})
      .then((mediaStreamObj) => {
      
         // Create a new MediaRecorder instance
         const medRec =new MediaRecorder(mediaStreamObj);
         window.mediaStream = mediaStreamObj;
         window.mediaRecorder = medRec;
         medRec.start();
         
         //when recorded data is available then push into chunkArr array
         medRec.ondataavailable = (e) => {chunksArr.push(e.data);};
         
         //stop the video recording
         medRec.onstop = () => {
            const blobFile = new Blob(chunksArr, { type:"video/mp4" });
         chunksArr= [];
         
         // create video element and store the media which is recorded
         const recMediaFile = document.createElement("video");
         recMediaFile.controls = true;
         const RecUrl = URL.createObjectURL(blobFile);
         
         //keep the recorded url as source
         recMediaFile.src = RecUrl;
         document.getElementById(`vid-recorder`).append(recMediaFile);
      };
      document.getElementById("vidBox").srcObject = mediaStreamObj;
      //disable the start button and enable the stop button
      startBtn.disabled = true;
      endBtn.disabled = false;
   });
}

When the start button is pressed, it will call the above function, which will trigger the WebRTC camera and microphone methods to get the recording permission, and will enable the stop recording button and disable the start recording button.

When the stop button is pressed, it will call the stop() function and stop all media streaming tracks.

Then in order to record the media stream, we will create a media recorder instance and make the media stream as well as the media reorder globally. Stopping the video will then stop the media streaming and creating the video element will create a new video element and store the recorded media data.

Similarly, the start_audio_Recording() function is also similar to the start_video_Recording() function, but requires some changes.

stop_Recording() function

Now let's define a function to stop recording.

function stop_Recording(end, start) {
   window.mediaRecorder.stop();
   
   // stop all tracks
   window.mediaStream.getTracks() .forEach((track) => {track.stop();});
   //disable the stop button and enable the start button
   end.disabled = true;
   start.disabled = false;
}

This function will stop all media tracks stored in the media stream.

Example

Let us add the above functions to the HTML code to implement video and audio recording functionality.

<!DOCTYPE html>
<html>
<head>
   <title>Video & Audio Recorder</title>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
   <style>
      body {
         text-align: center;
         color: red;
         font-size: 1.2em;
      }
      //video start & end, Audio start & end button styling
      #video_st, #video_en, #aud_st, #aud_en{
         margin-top: 10px;
         padding: 10px;
         border-radius: 4px;
         cursor: pointer;
      }
      #vidBox{
         background-color: grey;
      }
      video {
         background-color: gray;
         display: block;
         margin: 6px auto;
         width: 420px;
         height: 240px;
      }
      audio {
         display: block;
         margin: 6px auto;
      }
      a {
         color: green;
      }
   </style>
</head>
<body>
  <h1 style="color:blue"> Video-Audio recorder</h1>
   <div class="display-none" id="vid-recorder">
      <h3>Record Video </h3>
      <video autoplay id="vidBox"> </video>
      <button type="button" id="video_st" onclick="start_video_Recording()"> <i class="fa fa-play"></i></button>
      <button type="button" id="video_en" disabled onclick="stop_Recording(this, document.getElementById('video_st'))">
         <i class="fa fa-stop"></i>
      </button>
   </div>
   <!-- ------------ -->
   <br>
   <hr>
   <!-- ------------ -->
   <div class="display-none" id="audio_rec">
      <h3> Record Audio</h3>
      <button type="button" id="aud_st"
      onclick="start_audio_Recording()"><i class="fa fa-play"></i>
      </button>
      <button type="button" id="aud_en"
      disabled onclick="stop_Recording(this, document.getElementById('aud_st'))"> <i class="fa fa-stop"></i></button>
   </div>
<script>

//----------------------Video-------------------------------------
function start_video_Recording() {
   //To stores the recorded media
   let chunks = [];
   const startBtn=document.getElementById("video_st");
   const endBtn=document.getElementById("video_en");
   
   // Access the camera and microphone
   navigator.mediaDevices.getUserMedia({audio: true, video: true})
   .then((mediaStreamObj) => {
   
      // Create a new MediaRecorder instance
      const medRec =new MediaRecorder(mediaStreamObj);
      window.mediaStream = mediaStreamObj;
      window.mediaRecorder = medRec;
      medRec.start();
      
      //when recorded data is available then push into chunkArr array
      medRec.ondataavailable = (e) => {
         chunks.push(e.data);
      };
      
      //stop the video recording
      medRec.onstop = () => {
         const blobFile = new Blob(chunks, { type:"video/mp4" });chunks = [];
      
         // create video element and store the media which is recorded
         const recMediaFile = document.createElement("video");
         recMediaFile.controls = true;
         const RecUrl = URL.createObjectURL(blobFile);
         
         //keep the recorded url as source
         recMediaFile.src = RecUrl;
         document.getElementById(`vid-recorder`).append(recMediaFile);
      };
      document.getElementById("vidBox").srcObject = mediaStreamObj;
      startBtn.disabled = true;
      endBtn.disabled = false;
   });
}
//--------------------audio---------------------------------------

function start_audio_Recording() {
   //To stores the recorded media
   let chunksArr = [];
   const startBtn=document.getElementById("aud_st");
   const endBtn=document.getElementById("aud_en");
   
   // Access the camera and microphone
   navigator.mediaDevices.getUserMedia({audio: true, video: false})
   .then((mediaStream) => {
      const medRec = new MediaRecorder(mediaStream);
      window.mediaStream = mediaStream;
      window.mediaRecorder = medRec;
      medRec.start();
      
   //when recorded data is available then push into chunkArr array
   medRec.ondataavailable = (e) => {
      chunksArr.push(e.data);
   };
   
   //stop the audio recording
      medRec.onstop = () => {
         const blob = new Blob(chunksArr, {type: "audio/mpeg"});
         chunksArr = [];
         
         // create audio element and store the media which is recorded
         const recMediaFile = document.createElement("audio");
         recMediaFile.controls = true;
         const RecUrl = URL.createObjectURL(blob);
         recMediaFile.src = RecUrl;
         document.getElementById(`audio_rec`).append(
         recMediaFile);
      };
      startBtn.disabled = true;
      endBtn.disabled = false;
   });
}
function stop_Recording(end, start) {
   //stop all tracks
   window.mediaRecorder.stop();
   window.mediaStream.getTracks() .forEach((track) => {track.stop();});
      //disable the stop button and enable the start button
      end.disabled = true;
      start.disabled = false;
   }
</script>
</body>
</html>

As can be seen from the output, when the video start button is clicked, it calls the start_video_Recording() function, and in that function calls the navigator.mediaDevices.getUserMedia() method, and opens a permissions menu for finding Video and microphone permissions. It returns a promise to parse the media stream. After receiving the audio or video media stream, it creates an instance of the media recorder and starts recording by calling the function medRec.start() in the above code.

Thus, you will understand the complete process of creating video and audio recordings using WebRTC.

The above is the detailed content of How to create video and audio recorders using the JavaScript MediaRecorder API?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete