DEV Community

William Boles
William Boles

Posted on

Converting a 100 MB WAV to MP3 in the browser without running out of memory

I run SoundBench, a set of audio tools that work entirely in the browser: nothing is uploaded, everything happens on the user's device.

A while ago I posted about it on Reddit, and someone left a fair comment: decoding a large WAV in the browser eats a lot of memory, and phones are the first to crash. They were right. My WAV to MP3 converter decoded the whole file into memory before encoding anything.

Here's how I rewrote it to stream instead.

Why the old way used so much memory

The simple approach looks like this:

  1. Read the whole file into an ArrayBuffer.
  2. Decode it into Float32 samples with the Web Audio API.
  3. Encode those samples to MP3.
  4. Collect the MP3 bytes and build a Blob.

A 10-minute stereo WAV at 44.1 kHz is about 106 MB on disk. Decoded to Float32 it doubles, and you're holding the original bytes, the decoded samples and the growing MP3 output at the same time. On a phone with a tight per-tab memory limit, that's game over.

The idea: never hold the whole file

WAV is one of the few formats where you don't need a decoder at all. After a small header, it's just raw PCM samples. So instead of decoding everything, you can:

  • read the header to learn the format,
  • read the audio in small slices with File.slice(),
  • convert each slice to 16-bit samples and hand it to the MP3 encoder,
  • throw the slice away and move on.

Step 1: Parse the header without reading the file

File.slice() gives you a lazy view, so reading the first few KB is cheap. A WAV file is a RIFF container made of chunks, and the two that matter are fmt (format) and data (samples). Other chunks (LIST, bext, etc.) can appear in any order, so you walk them instead of assuming fixed offsets.

async function readAt(file, start, length) {
  return new DataView(await file.slice(start, start + length).arrayBuffer());
}

async function wavLayout(file) {
  const head = await readAt(file, 0, 12);
  if (head.getUint32(0) !== 0x52494646 /* RIFF */ || head.getUint32(8) !== 0x57415645 /* WAVE */) return null;
  let pos = 12, fmt = null;
  while (pos + 8 <= file.size) {
    const chunk = await readAt(file, pos, 8);
    const id = chunk.getUint32(0), size = chunk.getUint32(4, true);
    if (id === 0x666d7420 /* "fmt " */) {
      const f = await readAt(file, pos + 8, Math.min(size, 40));
      fmt = { tag: f.getUint16(0, true), channels: f.getUint16(2, true),
              rate: f.getUint32(4, true), bits: f.getUint16(14, true) };
    } else if (id === 0x64617461 /* "data" */ && fmt) {
      // some recorders write 0 or 0xFFFFFFFF here: read to the end of the file
      const end = (size === 0 || size === 0xFFFFFFFF) ? file.size : pos + 8 + size;
      return { ...fmt, start: pos + 8, end: Math.min(end, file.size) };
    }
    pos += 8 + size + (size & 1); // chunks are padded to an even size
  }
  return null;
}
Enter fullscreen mode Exit fullscreen mode

Two real-world details that bit me:

  • WAVE_FORMAT_EXTENSIBLE (tag 0xFFFE): many 24-bit and multichannel files use it, and the real format code lives inside the extension. You have to read it to know whether the samples are integer PCM or float.
  • Data size of 0 or 0xFFFFFFFF: some recorders write it before they know the final length. Treat it as "until the end of the file".

Step 2: Stream, convert, encode

MP3 works in frames of 1152 samples, so I read slices that are a whole number of frames (about 2.3 MB each), convert every sample to 16-bit, and feed the encoder.

The output needs care too. If you keep pushing small Uint8Arrays into an array, you end up with thousands of objects. Instead, every ~8 MB I fold the pending pieces into a Blob. Browsers can keep Blob data out of the JS heap, so the heap stays flat no matter how long the file is.

const parts = [];
let pending = [], pendingBytes = 0;
function push(bytes) {
  if (!bytes.length) return;
  pending.push(bytes); pendingBytes += bytes.length;
  if (pendingBytes > 8 * 1024 * 1024) {
    parts.push(new Blob(pending)); pending = []; pendingBytes = 0;
  }
}
Enter fullscreen mode Exit fullscreen mode

Between slices I yield to the event loop, so the progress bar keeps moving and the page never freezes.

Step 3: Know when not to stream

Streaming only covers what's simple to handle exactly: PCM at 8, 16, 24 or 32 bits, 32/64-bit float, mono or stereo, at sample rates MP3 supports. Anything else (resampling, more channels, unusual codecs inside a WAV) falls back to the old full-decode path. The function just returns null and the caller uses the original route, so no file is ever worse off than before.

Results

  • A 10-minute, 106 MB WAV converted in about 59 seconds, with the JS heap growing by only ~30 MB instead of several hundred.
  • The MP3 output was byte-identical to the old path for every format I tested, because the sample conversion uses exactly the same formula.
  • Large files now work on phones that used to crash the tab.

Takeaways

  • Before reaching for a decoder, check if the format is simple enough to read directly. WAV almost always is.
  • File.slice() plus Blob folding is a cheap, effective way to keep memory flat in the browser.
  • Always keep the old path as a fallback. Streaming is an optimization, not a replacement.

The converter is free to use here: soundbench.net/wav-to-mp3/. Thanks to the Redditor who pointed out the problem. Feedback on the approach is very welcome.

Top comments (0)