Enton Biba LogoEnton Biba

Record Microphone with Web Audio API

Date: January 07, 2023 Web Audio APIRecord MicrophoneJavascriptMicrophoneSounds
Record Microphone with Web Audio API

How to record microphone and save as wav format using Web Audio API.

Below you will find sample code on how to record audio from microphone and save the audio data as a wav file format.




class YourWorkletProcessor extends AudioWorkletProcessor {
    process(inputs, outputs, parameters) {
        // Get the audio data from the input buffer
        const inputData = inputs[0][0];

        // Output the processed data

        // Return true to indicate that the node should continue processing
        return true;

registerProcessor('your-worklet-processor-name', YourWorkletProcessor);



let recordingBuffer = [];

// Request microphone access
  .then(() => {

    navigator.mediaDevices.getUserMedia({ audio: true })
      .then(stream => {
            // Create an AudioContext
            const audioContext = new AudioContext();

            // Create a MediaStreamSource node to feed the stream into the audio context
            const source = audioContext.createMediaStreamSource(stream);

            // Create a AudioWorkletNode to process the audio data
            const workletNode = new AudioWorkletNode(audioContext, 'your-worklet-processor-name');

            // Connect the source to the script processor

            // Connect the script processor to the destination (the speakers)

            // Function to export the recording as a WAV file
            function exportWAV() {
                // Create a new AudioContext to process the data
                const exportAudioContext = new AudioContext();

                // Create a Float32Array to hold the entire recording
                const recordedData = mergeBuffers(recordingBuffer, recordingBuffer.length);

                // Create a buffer source to process the data
                const bufferSource = exportAudioContext.createBufferSource();
                const buffer = exportAudioContext.createBuffer(1, recordedData.length, exportAudioContext.sampleRate);
                bufferSource.buffer = buffer;

                // Use the built-in encodeWAV method to create the WAV file
                const encodedWAV = exportAudioContext.encodeWAV(bufferSource.buffer);

                // Create a Blob from the encoded WAV data
                const blob = new Blob([encodedWAV], { type: 'audio/wav' });

                // Create a link to download the file
                const downloadLink = document.createElement('a');
                downloadLink.href = URL.createObjectURL(blob);
                downloadLink.download = 'recording.wav';

                // Add the link to the DOM and simulate a click to start the download

                // Remove the link from the DOM
      .catch(err => {
        console.error('Failed to get microphone access:', err);