Back to Blog
Technicalaudiomp3lamejs

Encoding MP3 in the Browser with lamejs

How MP3 encoding works in the browser with lamejs: 1152-sample frames, converting float audio to 16-bit samples, what a bitrate really buys you, and why re-encoding a lossy file costs quality.

LoopalooPublished April 10, 202610 min read

Browsers are great at decoding audio. Give the Web Audio API a File in almost any common format (MP3, WAV, OGG, M4A) and decodeAudioData hands you back a tidy AudioBuffer full of floating-point samples. The trouble starts when you want to go the other way. There is no built-in MP3 encoder anywhere in the browser. The platform will happily turn an MP3 into PCM, but it will not turn your PCM back into an MP3.

That asymmetry is the whole reason a library like lamejs exists. It is a JavaScript port of the venerable LAME MP3 encoder, so it runs entirely on the client, with no server and no upload of anyone's audio. That makes it a natural fit for web tools that edit audio in the browser and need to hand back a downloadable .mp3 at the end.

This post walks through how an AudioBuffer becomes a stream of MP3 frames, why the samples have to be converted from float to 16-bit integers first, what the number 1152 is doing in the encode loop, and what "192 kbps" really buys you. It ends with the caveat that matters most: re-encoding audio that is already lossy is never free.

The shape of the problem

Web Audio always decodes to 32-bit float PCM. Each channel is a Float32Array in which every sample sits in the range -1.0 to +1.0. Float is convenient for DSP because you can multiply, add and filter samples without worrying about clipping or integer overflow mid-calculation; intermediate values can briefly exceed the nominal range, and you clamp only at the end.

MP3 encoders, on the other hand, take 16-bit integer PCM as their input convention. LAME (and therefore lamejs) expects each sample as an Int16, in the range -32768 to +32767. So before any encoding can happen there is an unavoidable conversion step: float to int.

A minimal converter looks like this:

function floatTo16Bit(input: Float32Array): Int16Array {
  const output = new Int16Array(input.length);
  for (let i = 0; i < input.length; i++) {
    const s = Math.max(-1, Math.min(1, input[i])); // clamp first
    output[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
  }
  return output;
}

Two details deserve a closer look. The first is the Math.max(-1, Math.min(1, ...)) clamp. After DSP work like gain changes or mixing, individual samples can drift outside [-1, 1]. If a value of 1.4 got through, multiplying by 0x7fff would overflow the Int16Array and wrap around to a large negative number: a loud, ugly click. Clamping first keeps a too-hot mix sounding like distortion rather than a glitch.

The second is the asymmetric scaling: negative samples multiply by 0x8000 (32768) and positive samples by 0x7fff (32767). That is not a typo. Two's complement 16-bit integers are not symmetric; they run from -32768 to +32767. Using the right maximum on each side covers the full available range without overflowing the positive end.

From AudioBuffer to encoder

With integers in hand, setting up the encoder is short. lamejs exposes an Mp3Encoder class that takes the channel count, the sample rate and the bitrate:

const channels = audioBuffer.numberOfChannels; // 1 or 2
const encoder = new lamejs.Mp3Encoder(channels, audioBuffer.sampleRate, 192);

const left = floatTo16Bit(audioBuffer.getChannelData(0));
const right = channels > 1 ? floatTo16Bit(audioBuffer.getChannelData(1)) : left;

The three constructor arguments map directly onto properties of the buffer:

ArgumentSourceMeaning
channelsaudioBuffer.numberOfChannels1 for mono, 2 for stereo
samplerateaudioBuffer.sampleRateusually 44100 or 48000 Hz
kbpsyour choicetarget bitrate of the output

For mono input, the snippet passes the left channel in the "right" slot as well. The encoder was constructed with one channel, so nothing is doubled; reusing the reference just saves a second conversion and keeps the encode loop identical for mono and stereo.

Two format limits are easy to trip over here. MP3 carries at most two channels, so a 5.1 buffer needs a downmix before it reaches the encoder. And MP3 supports only a fixed set of sample rates: 32, 44.1 and 48 kHz for MPEG-1, plus half and quarter rates for the MPEG-2 and MPEG-2.5 extensions. A 96 kHz recording has to be resampled to one of those first.

There is also a practical wrinkle with lamejs itself. It predates ES modules, and its original package has a long-standing problem with modern bundlers, where builds fail at runtime with errors such as MPEGMode is not defined. The usual workarounds are to load the prebuilt lame.min.js as a plain script and read the lamejs global, or to use one of the community forks that repackage it as a proper module. Either way, it pays to load the encoder lazily, only when someone actually exports an MP3, and to cache the loading promise so the script is fetched once per page.

Why 1152? The sample block loop

This is the part that surprises people. You do not feed the whole song to the encoder at once. You feed it in blocks of 1152 samples per channel:

const BLOCK = 1152;
const chunks: Int8Array[] = [];

for (let i = 0; i < left.length; i += BLOCK) {
  const out = encoder.encodeBuffer(
    left.subarray(i, i + BLOCK),
    right.subarray(i, i + BLOCK),
  );
  if (out.length > 0) chunks.push(out);
}

const tail = encoder.flush();
if (tail.length > 0) chunks.push(tail);

1152 is not arbitrary. It is the number of PCM samples in a single MP3 frame in MPEG-1 Layer III, which internally works on two granules of 576 samples each (576 times 2 is 1152). The lamejs documentation suggests feeding blocks that are a multiple of 576 to make the encoder's job easier, and 1152 lines each call up with exactly one frame's worth of input.

A few mechanical points about the loop:

  • subarray is a view, not a copy. It returns a window onto the same underlying Int16Array buffer, so slicing the audio into thousands of blocks does not allocate thousands of new sample arrays. It also clamps an end index past the last sample, so the final short block needs no special case. Only the resulting MP3 bytes get collected.
  • encodeBuffer can return zero bytes. MP3 encoding has internal latency: the encoder buffers a little audio before it emits a complete frame. Early calls may return an empty Int8Array, which is why every push checks the length first.
  • flush() is mandatory. When the input runs out, the encoder is still holding the tail of the last partial frame. flush() drains it and writes the final bytes. Skip it and you lose the end of your audio.

Even with a clean flush, the MP3 comes out slightly longer than the source. The encoder adds a short delay at the start, and the last frame is padded out to a full 1152 samples, so expect a few tens of milliseconds of extra silence. That rarely matters for a podcast, but it is worth knowing if you are cutting loops that have to repeat without a gap.

The collected chunks can go straight into a Blob, since the Blob constructor accepts typed arrays and respects each one's offset and length:

const mp3 = new Blob(chunks, { type: 'audio/mpeg' });

If you need one contiguous buffer instead (to hand to another API, say), copy the chunks into it:

const total = chunks.reduce((sum, c) => sum + c.length, 0);
const bytes = new Uint8Array(total);
let offset = 0;
for (const c of chunks) {
  bytes.set(new Uint8Array(c.buffer, c.byteOffset, c.length), offset);
  offset += c.length;
}

Wrapping each chunk as new Uint8Array(c.buffer, c.byteOffset, c.length) reinterprets the signed bytes as unsigned ones without changing them, and passing the offset and length matters: if a chunk is a view into a larger buffer, wrapping c.buffer alone would copy the wrong bytes.

What 192 kbps actually means

192 kbps is one of the most common defaults for MP3 export. So what is a bitrate?

Bitrate is the size of the output measured in time, not in samples. 192 kbps means 192,000 bits, or 24 kilobytes, of MP3 data per second of audio, regardless of how many samples that second contained. It is a budget. The encoder gets to spend that many bits per second describing the sound, and its psychoacoustic model decides where to spend them, throwing away detail that human hearing is least likely to notice.

That gives a simple, format-independent way to estimate the size of a constant-bitrate file:

size in bytes = bitrate in kbps × 1000 × duration in seconds ÷ 8

A three-minute (180 second) track at 192 kbps works out to 192 × 1000 × 180 ÷ 8 = 4,320,000 bytes, about 4.3 MB, and the sample rate barely changes that. Here are the common rungs (arithmetic from the same formula, not measured outputs):

BitrateRough useSize per 3 min
128 kbpsacceptable, smaller files~2.9 MB
192 kbpsgood general quality~4.3 MB
256 kbpshigh quality~5.8 MB
320 kbpsthe MP3 ceiling~7.2 MB

192 is a deliberate middle. It is widely considered transparent for casual listening on most material while keeping files small, which is why so many tools default to it.

One nuance: passing a higher bitrate to the encoder does not restore detail that was already thrown away upstream. It only raises the ceiling on how much the encoder is allowed to keep. If your source is a 128 kbps MP3 that you decoded and processed, encoding the result at 320 kbps gives you a bigger file, not a better-sounding one.

The lossy re-encode caveat

MP3 is a lossy codec. Encoding to MP3 permanently discards audio information that the psychoacoustic model bets you will not miss. Decoding it back to PCM does not recover that information; it reconstructs an approximation.

So when a tool loads an MP3, decodes it to an AudioBuffer, changes the samples, and encodes back to MP3, you are stacking two lossy passes. The first happened whenever the file was originally made; the second happens on the way out. Each generation compounds small artifacts, the same way photocopying a photocopy slowly smears the page. For a single round trip at 192 kbps the difference is usually inaudible on typical playback gear, but it is real, and it accumulates if you keep running the same file through again and again.

There are two ways to avoid the second loss when you do not need MP3:

  • Keep the output as WAV, which stores PCM directly with no perceptual compression. It is the right choice whenever the file is an intermediate step on the way to more editing.
  • Encode from the highest-quality source you have, once, rather than processing an already-compressed export several times.

If MP3 really is the target format (for compatibility, for sharing, for a device that only plays MP3), a single 192 kbps pass is a perfectly reasonable trade. Just go in knowing it is a one-way door, not a lossless container.

Where this runs on Loopaloo

Loopaloo's audio tools encode in the tab, so your audio never leaves the browser, and most of them let you choose between MP3 and lossless WAV at export:

  • Audio Speed Adjuster and Pitch Shifter each offer WAV (16-bit, lossless) or MP3 at 192 kbps.
  • Audio Merger offers 16-bit or 24-bit WAV, or MP3 at 128, 192, 256 or 320 kbps. It also points out that the MP3 comes out about 30 to 50 ms longer than the WAV, which is the encoder delay and padding described above.
  • Audio Format Converter writes MP3 alongside OGG Vorbis, AAC, M4A, FLAC and WAV. For MP3 it has Low, Standard, High and Maximum presets (128, 192, 256 and 320 kbps) plus a slider from 64 to 320 kbps, and after converting it shows the file size and effective bitrate it actually wrote, so you can check the formula above against a real file.

Whichever tool you use, the MP3 you download was assembled frame by frame from your own samples, on your own machine.

Related Tools

Related Articles