How can I write an array of audio samples to a wav file with Node.js?

2.5k Views Asked by At

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.

2

There are 2 best solutions below

4
On

This can be done using the minimal package node-wav and a snippet similar to the one below:

First, install the dependency:

npm i node-wav

Then, use something like

let fs = require('fs');
let wav = require('node-wav');

// Parameters for the below data
const size =  5000
const amplitude = 128
const sampleRate = 20

// Generate some random data for testing
const data = (new Array(3)).fill((new Array(size)).fill(Math.random() * amplitude))

let buffer = wav.encode(data, { sampleRate: sampleRate, float: true, bitDepth: 32 });

fs.writeFile("test.wav", buffer, (err) => {
  if (err) return console.log(err);

  console.log("test.wav written");
});

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

4
On

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.