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.

 

JavaScript


// Request microphone access
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 ScriptProcessorNode to process the audio data
        const scriptProcessor = audioContext.createScriptProcessor(4096, 1, 1);

        // Connect the source to the script processor
        source.connect(scriptProcessor);

        // Connect the script processor to the destination (the speakers)
        scriptProcessor.connect(audioContext.destination);

        // Start recording when the script processor receives input
        scriptProcessor.onaudioprocess = function(event) {
            // Get the audio data from the input buffer
            const inputData = event.inputBuffer.getChannelData(0);

            // Append the data to a buffer for later processing
            recordingBuffer.push(new Float32Array(inputData));
        };

        // 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);
            buffer.getChannelData(0).set(recordedData);
            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
            document.body.appendChild(downloadLink);
            downloadLink.click();

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