lamejs

1.2.1 · maintenance · verified Sun Apr 19

lamejs is a pure JavaScript MP3 encoder library, initially a rewrite of jump3r-code which itself was based on libmp3lame. It enables client-side and server-side (Node.js) encoding of raw PCM audio data (specifically Int16Array samples) into MP3 format. The project highlights its performance, claiming to be significantly faster than real-time on various machines and environments (browser and Node.js). The current stable version is 1.2.1, released after a considerable hiatus, primarily to address a TypeScript compatibility issue. Its release cadence is slow, suggesting a maintenance rather than actively developed status. Key differentiators include its pure JavaScript implementation, making it suitable for browser-based audio processing without WASM, and its reported high encoding speed. It's particularly useful for scenarios requiring on-the-fly MP3 generation from Web Audio API outputs or other PCM sources.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Mp3Encoder, feed it audio samples in chunks, and then flush the buffer to finalize the MP3 data. It covers both mono encoding and the necessary steps to collect the encoded segments.

import { Mp3Encoder } from 'lamejs';

const channels = 1; // 1 for mono, 2 for stereo
const sampleRate = 44100; // 44.1khz (normal mp3 samplerate)
const kbps = 128; // encode 128kbps mp3

// Create a new MP3 encoder instance
const mp3encoder = new Mp3Encoder(channels, sampleRate, kbps);

// Create some dummy audio samples (one second of silence in Int16Array)
const samples = new Int16Array(sampleRate * channels);

const sampleBlockSize = 1152; // Can be anything, but multiple of 576 is efficient
const mp3Data = [];

// Process audio samples in chunks
for (let i = 0; i < samples.length; i += sampleBlockSize) {
  const sampleChunk = samples.subarray(i, i + sampleBlockSize);
  const mp3buf = mp3encoder.encodeBuffer(sampleChunk);
  if (mp3buf.length > 0) {
    mp3Data.push(mp3buf);
  }
}

// Flush the encoder to get any remaining data
const mp3buf = mp3encoder.flush();
if (mp3buf.length > 0) {
    mp3Data.push(new Int8Array(mp3buf)); // Ensure it's Int8Array for Blob creation
}

// For browser environments, you can create a Blob and a URL
// const blob = new Blob(mp3Data, { type: 'audio/mp3' });
// const url = window.URL.createObjectURL(blob);
// console.log('Generated MP3 URL:', url);

// In Node.js, you might write to a file system
// import { writeFileSync } from 'fs';
// writeFileSync('output.mp3', Buffer.concat(mp3Data.map(arr => Buffer.from(arr))));

console.log('MP3 encoding complete. Total buffers:', mp3Data.length);
console.log('First buffer length:', mp3Data[0]?.length || 0);

view raw JSON →