How to record audio to file with JavaScript?

Sometimes, we want to record audio to file with JavaScript.

In this article, we’ll look at how to record audio to file with JavaScript.

How to record audio to file with JavaScript?

To record audio to file with JavaScript, we use the MediaRecorder API.

For instance, we write

let audioChunks = [];
let rec;

navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
  handlerFunction(stream);
});

const sendData = (blob) => {
  //...
};
const handlerFunction = (stream) => {
  rec = new MediaRecorder(stream);
  rec.ondataavailable = (e) => {
    audioChunks.push(e.data);
    if (rec.state == "inactive") {
      let blob = new Blob(audioChunks, { type: "audio/mp3" });
      recordedAudio.src = URL.createObjectURL(blob);
      recordedAudio.controls = true;
      recordedAudio.autoplay = true;
      sendData(blob);
    }
  };
};

record.onclick = (e) => {
  record.disabled = true;
  record.style.backgroundColor = "blue";
  stopRecord.disabled = false;
  audioChunks = [];
  rec.start();
};

stopRecord.onclick = (e) => {
  record.disabled = false;
  stop.disabled = true;
  record.style.backgroundColor = "red";
  rec.stop();
};

to check if we have audio permission with

navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
  handlerFunction(stream);
});

If we have then we call handlerFunction to handle the stream.
We record the audio by calling rec.start, where rec is a MediaRecorder instance we created with the stream.

And in the stopRecord.onclick method, we call rec.stop to stop recording.

Then if we check that rec.state is 'inactive', we create an mp3 blob from the recorded audio with

let blob = new Blob(audioChunks,{type:'audio/mp3'});

Then we can set URL.createObjectURL(blob); as the src property of the recordedAudio audio element so we can play the recorded audio.

Conclusion

To record audio to file with JavaScript, we use the MediaRecorder API.