How to record and play audio in JavaScript?


Are you also willing to add a custom audio recording feature to your web application? If yes, you are in the right place, as we will learn to record and play audio using JavaScript in this tutorial.

Some applications like Discord allow you to record the audio and store it inside that to play it anytime. The recorded audio can also be used as a meme for fun, alerts in the discord meetings, etc.

We can also use the mediaRecorder API of JavaScript to add the recording audio feature to our web application. Here, we will learn a step-by-step guide to recording, storing, and playing audio.

Syntax

Users can follow the syntax below to record and play audio using the mediaRecorder API.

navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
   audioRecorder = new MediaRecorder(stream);
   audioRecorder.start();
   audioRecorder.stop();
   const blobObj = new Blob(audioChunks, { type: 'audio/webm' });
   const audioUrl = URL.createObjectURL(blobObj);
   const audio = new Audio(audioUrl);
   audio.play();
})

Parameters and Methods Explained

  • Navigator.mediaDevice − The mediaDevice object provides access to the media related functionality such as audio and video stream.

  • getUserMedia() − The getUserMedia() method request the user’s media stream’s permission. It takes the object containing the type of media streams as a parameter. Here we used the { audio : true } to access the audio stream and ask for the permission of the microphone.

  • Stream − We passed it as a parameter of the callback function, which we get after users approve the permission.

  • MediaRecorder − We can use the MediaRecorder() constructor by passing the stream variable as a parameter to create a new media recorder.

  • Start() − It is used to start recording.

  • Stop() − It is used to stop recording.

  • Blob() − It is used to convert audio chunks in the blob object.

  • createObjectURL() − It creates audio URLs from the blob object.

  • Audio() − It converts audio URLs to audio.

  • Play() − It is used to play the audio URL.

Example

We added the start, stop, and play recording buttons in the example below. In JavaScript, we access the media stream of users' devices, and after that, we initialize the media recorder object using the media stream.

Next, we invoke the method based on the button clicked and store the recorder audio in the ‘audioChunks’ array. Also, we used the catch() block to catch errors while recording the audio.

In the output, users can click the start recording button to start the recording. After that, click the stop recording button once the recording completes. Next, click the play recording button to play the recorded video.

<html>
<head>
   <style>
      button {margin: 5px; padding: 10px 20px; background-color: #007bff; color: #fff; border: none; border-radius: 5px; cursor: pointer;}
      button:hover {background-color: #0056b3;}
      div { margin-top: 20px;}
   </style>
</head>
<body>
   <h3> Using the Media recorder API to record the audio in the web browser </h3>
   <div>
      <button id = "start"> Start Recording </button>
      <button id = "stop"> Stop Recording </button>
      <button id = "play"> Play Recorded Audio </button>
   </div> <br> 
   <div id = "output"> </div>
   <script>
      const startButton = document.getElementById('start');
      const stopButton = document.getElementById('stop');
      const playButton = document.getElementById('play');
      let output = document.getElementById('output');
      let audioRecorder;
      let audioChunks = [];
      navigator.mediaDevices.getUserMedia({ audio: true })
         .then(stream => {
         
            // Initialize the media recorder object
            audioRecorder = new MediaRecorder(stream);
            
            // dataavailable event is fired when the recording is stopped
            audioRecorder.addEventListener('dataavailable', e => {
               audioChunks.push(e.data);
            });
            
            // start recording when the start button is clicked
            startButton.addEventListener('click', () => {
               audioChunks = [];
               audioRecorder.start();
               output.innerHTML = 'Recording started! Speak now.';
            });
            
            // stop recording when the stop button is clicked
            stopButton.addEventListener('click', () => {
               audioRecorder.stop();
               output.innerHTML = 'Recording stopped! Click on the play button to play the recorded audio.';
            });
            
            // play the recorded audio when the play button is clicked
            playButton.addEventListener('click', () => {
               const blobObj = new Blob(audioChunks, { type: 'audio/webm' });
               const audioUrl = URL.createObjectURL(blobObj);
               const audio = new Audio(audioUrl);
               audio.play();
               output.innerHTML = 'Playing the recorded audio!';
            });
         }).catch(err => {
         
            // If the user denies permission to record audio, then display an error.
            console.log('Error: ' + err);
         });
   </script>
</body>
</html>

In this tutorial, users learned to use the mediaRecorder API to record the media. Developers can allow users to record audio and store it in the local storage to allow users to play recorded audio repeatedly, even after reloading the web page.

Updated on: 26-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements