This article describes how to record audio using the Web Audio API in JavaScript. The related resources are shown below.
The workflow is shown below.
- Coding preparation
- Coding
- Operation check
Run the following commands to parepare for coding.
mkdir javascript-audio-recorder
cd javascript-audio-recorder
npm init -y
npm install --save-dev http-server
touch audio-recorder.js encode-audio.js index.html main.js
Open index.html in you editor and enter the following content.
Open index.html in you editor and enter the following content.
The points are shown below.
- Define the isRecording parameter.
- Store the sample into the buffer when the isRecording parameter is 1.
- Send a message when the number of elements in the buffer is 1 or more.
- Register the Audio Recorder as an Audio Worklet.
Open encode-audio.js in you editor and enter the following content.
Click to go to encode-audio.js
Open main.js in you editor and enter the following content.
The points are shown below.
- Get the media stream to capture the audio from the microphone.
- Get the settings such as resolution and sampling frequency.
- Load the module from audio-recorder.js.
- Create a node to handle the media stream.
- Create a node to use the worklet.
- Set the event handler when a message is received from the worklet.
- Start receiving messages from the worklet.
- Connect media streams, worklets and speakers. Since the worklet does not output anything, no sound is played from the speaker.
- Set the worklet's isRecording parameter to 1 to start recording.
- Set the worklet's isRecording parameter to 0 to stop recording.
- Call the encodeAudio function to convert the recorded audio to WAVE format.
Just opening index.html in your web browser will fail to call audioContext.audioWorklet.addModule, so run the following command to start the web server.
npx http-server -c-1
Go to http://localhost:8080 in your web browser.
You will be asked to allow access to the microphone, so click the "Allow" button.
Click the Start button to start recording.
Click the "Stop" button to stop recording.
Click the play button to play the audio.
The web pages that I referred to when writing the article are shown below.
- mattdiamond/Recorderjs: A plugin for recording/exporting the output of Web Audio API nodes
- An example of a recorder based on AudioWorklet API.
There is also a way to record audio using the MediaStream Recording API, which is easier. For details on how to use the MediaStream Recording API, see How to record audio using the MediaStream Recording API with JavaScript. I would appreciate it if you could take a look. Thank you for reading!
MIT
@juliusb97
Thank you for your comment!
I fixed it π