Member-only story

How to Convert Audio From Wav to MP3 in Node.js Using FFMpeg

Adam Berg
2 min readNov 7, 2021

Uncompressed live music is best

Update: I’ve added a new post describing how to do this client-side.

While working on kaizen.place, a music app that encourages continuous improvement of your music, I found a need to convert wav files to mp3. To keep hosting costs down, I set a limit of 10 MB for the file upload size. But a standard 3 minute song is just over 30 MB. Indirectly, this limit meant that for a full song, artists were required to upload mp3 files.

After hearing about (and seeing first hand) the annoyance of getting ready to upload a new version of a song, I figured it would probably be worth it to allow users to upload larger wav files, but then convert them to mp3. On average an mp3 converted track takes up about one tenth of the space of a wav . This essentially means that wav files up to almost 100 MB can now be accepted without using more than 10 MB of storage space.

This post condenses the info that I picked up from several different sources to hopefully give you enough info for your next audio project.

Install fluent-ffmpeg

npm install fluent-ffmpegoryarn add fluent-ffmpeg

Installing ffmpeg

fluent-ffmpeg is just a small layer on top of the ffmpeg program. You therefore must have ffmpeg installed

Ubuntu

apt-get install ffmpeg

Mac

brew install ffmpeg

Windows

Go download Ubuntu and install it at least on a partition of your hard drive. You’ll thank me later.

The Final Code

import ffmpeg from "fluent-ffmpeg";
import path from "path";
function isWavFile(wavFilename: string) {
const ext = path.extname(wavFilename);
return ext === ".wav";
}
function convertWavToMp3(wavFilename: string): Promise<string> {
return new Promise((resolve, reject) => {
if (!isWavFile(wavFilename)) {
throw new Error(`Not a wav file`);
}
const outputFile = wavFilename.replace(".wav", ".mp3");
ffmpeg({
source: wavFilename,
}).on("error", (err) => {
reject(err);
}).on("end", () => {
resolve(outputFile);
}).save(outputFile);
});
}

Conclusion

And there you have it. The above code loads a wav file from the filesystem and converts it to an mp3 .

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Adam Berg
Adam Berg

Written by Adam Berg

Building https://kaizen.place. writing about C, C++, rust, game development, web development, engineering management. https://devtails.xyz/

Responses (1)

Write a response