How to record audio to file with JavaScript?

Spread the love

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 canm savbe the stream to a blob.

For instance, we write

const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const rec = new MediaRecorder(stream);
const audioChunks = [];

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

to call getUserMedia to get permission to record audio.

Then we create a MediaRecorder object to record the audio stream.

Next we get the data from the rec.ondataavailable method.

In it, we push the recorded audio chunk into the audioChunks array.

Then we check if rec.state is 'inactive'.

If it is, we then we combine the chunks in the audioChunks array into a blob.

Then we set the recordedAudio audio element’s src property to the base64 URL version of the blob so we can play it back with that.

Conclusion

To record audio to file with JavaScript=, we canm savbe the stream to a blob.

Leave a Reply

Your email address will not be published. Required fields are marked *