Saving an AudioBuffer from AudioContext as a WAV file

This article can be read in about 4 minutes.
PR

The purpose


We will save an AudioBuffer, which is commonly used with AudioContext in JavaScript, as a local WAV file.

PR

Environment

I am using the following environment.

NodeJS + Vite

audiobuffer-to-wav

PR

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.

PR

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).

PR

Result

I was able to convert the AudioBuffer to a WAV file and save it locally.

PR

Reference

GitHub - Experience-Monks/audiobuffer-to-wav: convert an AudioBuffer to .wav format
convert an AudioBuffer to .wav format. Contribute to Experience-Monks/audiobuffer-to-wav development by creating an account on GitHub.

comment

Copied title and URL