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">
<script src="/app.js" async defer></script>
<input type="file" id="uploader">
<audio id="track" controls></audio>

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'-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");

Start the Server

node server.js




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@, hacking on writing about rust, web development, engineering management.