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

Create Project With JavaScript Bundler

npm initORyarn init

Add esbuild

yarn add --dev esbuild

Add Build Script

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

Add public/index.html

<html lang="en"><head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ffmpeg.wasm</title>
<script src="/app.js" async defer></script>
</head>
<body>
<input type="file" id="uploader">
<div>
<audio id="track" controls></audio>
</div>
</body>
</html>

Install ffmpeg

# Use npm
$ npm install @ffmpeg/ffmpeg
# Use yarn
$ yarn add @ffmpeg/ffmpeg

Add src/app.js

const { createFFmpeg } = require('@ffmpeg/ffmpeg');// The log true is optional, shows ffmpeg logs in the console
const ffmpeg = createFFmpeg({ log: true });
const transcode = async ({ target: { files } }) => {
const { name } = files[0];
// This loads up the ffmpeg.wasm files from a CDN
await ffmpeg.load();
const arrayBuffer = await files[0].arrayBuffer()
const uint8Array = new Uint8Array(arrayBuffer);
ffmpeg.FS("writeFile", name, uint8Array);
await ffmpeg.run('-i', name, 'test.mp3');
const data = ffmpeg.FS('readFile', 'test.mp3');
const track = document.getElementById("track");
track.src = URL.createObjectURL(new Blob([data.buffer], { type: 'audio/mpeg' }));
}
const uploader = document.getElementById('uploader')
uploader.addEventListener('change', transcode);

Build public/app.js Bundle

yarn build

Attempt (and fail) to Open This With a Simple Http Server

Adding a Simple Express Server

Install express

yarn add express

Create server.js

const express = require("express");const app = express();app.use((req, res, next) => {
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
next();
});
app.use(express.static("public"))app.listen(4242)

Start the Server

node server.js

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Berg

Adam Berg

VPE@https://dubsado.com, hacking on https://kaizen.place. writing about rust, web development, engineering management. https://devtails.xyz/