/ web-audio

Turn your browser into an audio recorder.

Have you ever wondered how you can record your microphone using javascript?
Since the MediaRecorder api landed in browsers it became very easy to do so.

To start we'll need to get access to the microphone. We can do this by using the getUserMedia method.

navigator.mediaDevices.getUserMedia({audio: true}).then(stream => {
    // All went well, here is an audio-stream of your microphone
}, error => {
    // Oops, something went wrong or your browser does not support mediaDevices.getUserMedia

Calling getUserMedia will return a promise, which when resolved will return an audio-stream of your microphone.
We will need this stream when creating a new MediaRecorder.

let recorder = null;

// We'll use these later!
const chunks = [];
const audioElement = document.querySelector('audio');

navigator.mediaDevices.getUserMedia({audio: true}).then(stream => {
    recorder = new MediaRecorder(stream);
    recorder.ondataavailable = saveChunkToRecording;
    recorder.onstop = saveRecording;

Once the new MediaRecorder has been created, we'll need to assign some eventhandlers.
The first one will be ondataavailable. This event will get fired every time a new chunk of audio is available.
We'll save all chunks of audio in an array, so we can process them later.
The saveChunkToRecording function will look something like this.

saveChunkToRecording(event) {

The second event we handle is the onstop event. This will get fired when the MediaRecorder has stopped recording.

saveRecording() {
    const blob = new Blob(chunks, {
        type: 'audio/mp4; codecs=opus'
    const url = URL.createObjectURL(blob);

    audioElement.setAttribute('src', url);

Our saveRecording function is going to combine all saved chunks of audio into on big Blob. With this Blob, we can create a data-url which we can set as the src of an <audio> element.

The only thing left to do is call the recorder.start() method to start recording and recorder.stop() to stop recording.
It is as simple as that, just plugin your MediaRecorder and you're done!

Here is a working demo. Take a look in the javascript tab of the Codepen to see the full working code.

See the Pen Record the audio input from your microphone by Sam (@Sambego) on CodePen.

Sam Bellen

Sam Bellen

Frontend developer at madewithlove - Co-organizer at Fronteers Belgium - Conference speaker - Cat lover

Read More