Skip to content
Related Articles

Related Articles

How to record and play audio in JavaScript ?
  • Difficulty Level : Basic
  • Last Updated : 25 Jun, 2020

JavaScript is a very flexible language and it provides many API support to do many useful things. Here one important thing is that record audio or video in web pages is also done using JavaScript. In this case, it will ask the user for microphone access to the browser and record the audio through the microphone and save the audio data chunks in form of binary value in an array and when we play the audio then retrieve chuck data and start playing. The same thing happens for video also, when we do video conferences then this actually happens in the server, only thing is that here we play the video at the same page, and in case of video conference the video will play at the other end.

This whole thing happens using an API, which is MediaRecorder API. This API provides functionality to record media such as audio or video. It is created using the MediaRecorder() constructor.

Here we use one property of JavaScript, which is mediaDevices property, which is used to get access to connected input media devices like microphones, webcams, etc. This property uses a method getUserMedia() to get permission for accessing the microphone, webcam etc. This method returns a promise to the navigator object.

The Promises are as follows:

If true:



  • resolve : If all permissions are achieved and the microphone or camera are working fine, then it returns a MediaStream object. This is the main recorded data.

If false:

  • NotAllowedError: If the user reject the permission for recording.
  • NotFoundError: If there is no media track.
  • NotReadableError: If the input devices are not found or the hardware is not working.
  • OverconstrainedError: If constraint audio settings are preventing.
  • AbortError: If generic unknown cause is found.
  • TypeError: If audio: false stated in the Javascript code.

Example:




<!DOCTYPE html>
<html>
  
<head>
  <script>
  
    let audioIN = { audio: true };
    //  audio is true, for recording
  
    // Access the permission for use
    // the microphone
    navigator.mediaDevices.getUserMedia(audioIN)
  
      // 'then()' method returns a Promise
      .then(function (mediaStreamObj) {
  
        // Connect the media stream to the
        // first audio element
        let audio = document.querySelector('audio');
        //returns the recorded audio via 'audio' tag
  
        // 'srcObject' is a property which 
        // takes the media object
        // This is supported in the newer browsers
        if ("srcObject" in audio) {
          audio.srcObject = mediaStreamObj;
        }
        else {   // Old version
          audio.src = window.URL
            .createObjectURL(mediaStreamObj);
        }
  
        // It will play the audio
        audio.onloadedmetadata = function (ev) {
  
          // Play the audio in the 2nd audio
          // element what is being recorded
          audio.play();
        };
  
        // Start record
        let start = document.getElementById('btnStart');
  
        // Stop record
        let stop = document.getElementById('btnStop');
  
        // 2nd audio tag for play the audio
        let playAudio = document.getElementById('adioPlay');
  
        // This is the main thing to recorde 
        // the audio 'MediaRecorder' API
        let mediaRecorder = new MediaRecorder(mediaStreamObj);
        // Pass the audio stream 
  
        // Start event
        start.addEventListener('click', function (ev) {
          mediaRecorder.start();
          // console.log(mediaRecorder.state);
        })
  
        // Stop event
        stop.addEventListener('click', function (ev) {
          mediaRecorder.stop();
          // console.log(mediaRecorder.state);
        });
  
        // If audio data available then push 
        // it to the chunk array
        mediaRecorder.ondataavailable = function (ev) {
          dataArray.push(ev.data);
        }
  
        // Chunk array to store the audio data 
        let dataArray = [];
  
        // Convert the audio data in to blob 
        // after stopping the recording
        mediaRecorder.onstop = function (ev) {
  
          // blob of type mp3
          let audioData = new Blob(dataArray, 
                    { 'type': 'audio/mp3;' });
            
          // After fill up the chunk 
          // array make it empty
          dataArray = [];
  
          // Creating audio url with reference 
          // of created blob named 'audioData'
          let audioSrc = window.URL
              .createObjectURL(audioData);
  
          // Pass the audio url to the 2nd video tag
          playAudio.src = audioSrc;
        }
      })
  
      // If any error occurs then handles the error 
      .catch(function (err) {
        console.log(err.name, err.message);
      });
  </script>
</head>
  
<body style="background-color:rgb(101, 185, 17); ">
  <header>
    <h1>Record and Play Audio in JavaScript</h1>
  </header>
  <!--button for 'start recording'-->
  <p>
    <button id="btnStart">START RECORDING</button>
                
    <button id="btnStop">STOP RECORDING</button>
    <!--button for 'stop recording'-->
  </p>
  
  <!--for record-->
  <audio controls></audio>
  <!--'controls' use for add 
    play, pause, and volume-->
  
  <!--for play the audio-->
  <audio id="adioPlay" controls></audio>
</body>
  
</html>

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :