How to Create a Video and Audio Recorder with JavaScript MediaRecorder API?


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

What is WebRTC?

WebRTC is a short form of Real-Time Communication. We can access and capture the Webcam and Microphone devices that are available there in the user device.

We can access the user device’s Webcam and microphone using an ECMAScript object

navigator.mediaDevices.getUserMedia(constraints).

So, the getUserMedia function by default, seeks user permission to use your Webcam. This function returns a promise and once you click ok and give the consent, then the function gets triggered and enables the webcam in your system, else in case you don’t allow then it also has a catch method that turns off the Webcam.

We can also pass a parameter to the function getUserMedia() function, which could be like we want a picture of some specific width or height.

Front-end design

Our frontend part will contain elements like −

For Video recording screen will have some elements like −

  • A video element that will display the video media screen

  • Start button will start the video recording

  • Stop button will stop the video recording stream.

For Audio recording also, it will have two buttons

  • Start button will start the audio recording

  • Stop button will stop the audio recording stream.

We will add font awesome CDN to add the start and stop buttons icon, and to make the page attractive, we will add CSS styling on 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 will click on the "start video" button then, it will call start_video_Recording() function and the "stop" button will call the stop_Recording() similarly for audio also clicking start button will trigger the function start_audio_Recording() and for stop button stop_Recording() function will get invoked.

start_video_Recording() function

Let define a function to start 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 will be pressed then it will call the above function which will trigger the WebRTC camera and microphone method to get access for recoding and it will enable the stop recoding and disable the start recording buttons.

When the stop button will be pressed then it will call stop() function and stop all the media streams tracks.

Then to record the media stream we will create a media recorder instance and make the media stream as well as media reorder global. Then stop video will stop the media stream and create video element will create a new video element and store the recorded media data.

Similarly start_audio_Recording() function is also similar to start_video_Recording() function with some required changes.

stop_Recording() function

Now let’s define a function to stop the 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 would stop all the media tracks which is stored in the media stream.

Example

Let’s add the above functions to the HTML code to make video and audio recordings functional.

<!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>

From the output it can be seen when the video start button is getting clicked then it calls the start_video_Recording() function and within that function navigator.mediaDevices.getUserMedia() method gets invoked and a permission menu open which seeks the video and microphone permission. It returns a promise which resolves the media stream. After it receives the media stream either audio or video it creates an instance of a media recorder and starts the recording by calling the function in the above code medRec.start().

So, you get to know about the complete procedure to create the video and audio recording using WebRTC.

Updated on: 01-Dec-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements