The purpose
We will save an AudioBuffer, which is commonly used with AudioContext in JavaScript, as a local WAV file.
Environment
I am using the following environment.
NodeJS + Vite
audiobuffer-to-wav
Install Environment
It is assumed that Node.js is already installed.
You will be asked for the project name, so enter one. (In this article, I have used wav.) When prompted for a framework, select Vanilla, and for the language, select JavaScript.
With these steps, the project creation is complete.
Install library
After the project has been created, you will install the necessary libraries.
cd wav
npm install
npm install audiobuffer-to-wav
That’s it, the setup is complete.
Code modification
Import
The import statement is written as follows.
import audioBufferToWav from "audiobuffer-to-wav"
Convert AudioBuffer to WAV
The conversion from audioBuffer
to WAV is the following single line.
const wav = audioBufferToWav(audioBuffer)
Regarding the audioBufferToWav arguments
The argument for audioBufferToWav
is audioBuffer
.
Looking at the code, this is the value that is set to the buffer
of an AudioBufferSourceNode
.
const source = audiocontext.createBufferSource();
source.buffer = audioBuffer;
Saving the Converted WAV File
The following code can be used to save the WAV file as out.wav
.
const audioBlob = new Blob([wav]);
const url = URL.createObjectURL(audioBlob);
const a = document.createElement("a")
a.href = url
a.download = "out.wav"
a.click()
TypeError: Failed to construct 'Blob': The object must have a callable @@iterator property.
When the above error occurs, please check if there are square brackets in new Blob([wav]);
.
You will get the error if you use new Blob(wav)
.
Result
I was able to convert the AudioBuffer to a WAV file and save it locally.
comment