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.



// 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

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

        // 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);
            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);
   = '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);