I'm writing an oscillator in JavaScript that creates a sweep(i.e. chirp) between sine wave frequencies. For testing, I'd like to write the samples(which are floats) to a wav file. How would I do this in Node.js? I've seen lots of information on the browser end of things but not anything specific to Node or anything that relies on browser APIs.
How can I write an array of audio samples to a wav file with Node.js?
2.5k Views Asked by Ten Bitcomb At
2
There are 2 best solutions below
4

You can use the built in Node.js fs.writeFile()
api to write to a file.
By the way I see it all you have to do is loop over your audio samples, add them to a string within the iteration, and put that string into a file like so:
const fs = require("fs");
// Code to generate audio
let audio = "";
samples.forEach((sample) => {
audio += sample;
});
fs.writeFile("path/to/file.wav or .mp3", audio, (err) => {
if (err) return console.error(err);
console.log("File successfully saved!");
});
If I'm understanding your question correctly, then this should work.
This can be done using the minimal package
node-wav
and a snippet similar to the one below:First, install the dependency:
Then, use something like
Considering that you already know the application of your data, you know all the "constant" parameters (size of the output, bitrate, the actual data to be written, bitdepth).