Member-only story

How to Convert Audio from wav to mp3 in JavaScript Using ffmpeg.wasm

Adam Berg
4 min readNov 9, 2021

--

Check out this basic demo at https://convert.devtails.xyz/and keep an eye out for client side audio conversions in https://kaizen.place/ .

I just posted the following article the other day about using fluent-ffmpeg to convert wavs to mp3s in node.

https://devtails.medium.com/how-to-convert-audio-from-wav-to-mp3-in-node-js-using-ffmpeg-e5cb4af2da6

I had initially pondered doing the conversion on the client side, but wasn’t immediately able to find something. An astute Reddit commentor pointed me to ffmpeg.wasm and here we are with a followup for how to make the same conversion, but this time inside the browser.

The ffmpeg.wasm project has a Getting Started page, that was mostly helpful, but it skips a couple critical steps that had me tripped up for a bit.

Create Project With JavaScript Bundler

If you don’t already have a project setup with a bundler, you can quickly spin up your own.

npm initORyarn init

This will make a package.json file. Feel free to just press enter through all the configuration options as the defaults will be just fine.

Add esbuild

yarn add --dev esbuild

I’ve written about esbuild in the past, and it will likely be a recurring theme as I try to figure out if it’s safe for production use. The benefit of it here is that there’s no ugly bundling configuration file to explain.

Add Build Script

Update package.json to add the following build script

"scripts": {
"build": "esbuild src/app.js --bundle --outfile=public/app.js --minify"
},

I experienced some interesting behaviour with the ffmpeg library. Without the --minify above, it attempts to load the ffmpeg-core files from http://localhost:4242/node_modules/@ffmpeg/core/dist/ffmpeg-core.wasm . In an earlier experiment I faced the same issue with webpack, I’m not sure what the issue is, but for these purposes a minified build works just fine.

Add public/index.html

--

--

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/

No responses yet

Write a response