### Start and Stop Audio Recording with Lame.js Source: https://github.com/gideonstele/lamejs/blob/master/worker-example/mic.html This JavaScript code handles the start and stop functionality for audio recording using Lame.js. It initializes an MP3 recorder, manages a timer during recording, and handles the conversion of recorded audio to an MP3 blob for playback. Dependencies include jQuery for DOM manipulation and the Lame.js library. ```javascript $(function () { var recorder = new MP3Recorder({ bitRate: 128 }), timer; $('#startBtn').on('click', function (e) { e.preventDefault(); var btn = $(this); recorder.start(function () { //start timer var seconds = 0, updateTimer = function(){ $('#timer').text(seconds < 10 ? '0' + seconds : seconds); }; timer = setInterval(function () { seconds++; updateTimer(); }, 1000); updateTimer(); //disable start button btn.attr('disabled', true); $('#stopBtn').removeAttr('disabled'); }, function () { alert('We could not make use of your microphone at the moment'); }); }); $('#stopBtn').on('click', function (e) { e.preventDefault(); recorder.stop(); $(this).attr('disabled', true); $('#startBtn').removeAttr('disabled'); //get MP3 clearInterval(timer); recorder.getMp3Blob(function (blob) { //var blobUrl = window.URL.createObjectURL(blob); blobToDataURL(blob, function(url){ $('ol.convertedList') .append('
  • recording_' + (new Date()) + '_.mp3
    ' + '' + '
  • '); }); }, function (e) { alert('We could not retrieve your message'); console.log(e); }); }); function blobToDataURL(blob, callback) { var a = new FileReader(); a.onload = function (e) { callback(e.target.result); } a.readAsDataURL(blob); } }); ``` -------------------------------- ### Install @breezystack/lamejs using pnpm or npm Source: https://github.com/gideonstele/lamejs/blob/master/README.md Instructions for installing the @breezystack/lamejs package using either pnpm or npm package managers. This is the first step to using the library in your project. ```bash pnpm add @breezystack/lamejs ``` ```bash npm install @breezystack/lamejs ``` -------------------------------- ### Convert WAV to MP3 in Browser using IIFE Source: https://context7.com/gideonstele/lamejs/llms.txt This example shows how to use lamejs in a web browser without a build system, leveraging the IIFE bundle. It allows users to select a WAV file, converts it to MP3 in the browser, and plays the resulting audio. It requires including the 'lamejs.iife.js' script in the HTML. ```html MP3 Encoder Demo ``` -------------------------------- ### ES Module Usage with lamejs in Modern JavaScript and TypeScript Source: https://context7.com/gideonstele/lamejs/llms.txt Demonstrates how to import and use lamejs components like Mp3Encoder and WavHeader in modern JavaScript projects using ES modules. It covers both named imports and namespace imports, and includes a TypeScript example with type annotations for creating an encoder and encoding audio buffers. ```javascript // Using named imports import { Mp3Encoder, WavHeader } from '@breezystack/lamejs'; const encoder = new Mp3Encoder(2, 44100, 192); // Using namespace import import * as lamejs from '@breezystack/lamejs'; const encoder2 = new lamejs.Mp3Encoder(1, 48000, 128); // TypeScript usage with type definitions import { Mp3Encoder, WavHeader } from '@breezystack/lamejs'; const createEncoder = (channels: number, sampleRate: number): Mp3Encoder => { return new Mp3Encoder(channels, sampleRate, 128); }; const encoder: Mp3Encoder = createEncoder(2, 44100); const leftChannel: Int16Array = new Int16Array(1152); const rightChannel: Int16Array = new Int16Array(1152); const mp3Data: Uint8Array = encoder.encodeBuffer(leftChannel, rightChannel); ``` -------------------------------- ### JavaScript Audio Conversion with Lame.js Source: https://github.com/gideonstele/lamejs/blob/master/worker-example/index.html This JavaScript code handles file uploads, MP3 conversion using Lame.js, and displays conversion progress. It requires the Lame.js library and jQuery for DOM manipulation. The input is a File object, and the output is an MP3 blob. ```javascript $(function () { var converter = new MP3Converter(); var file; $('#audioReceiver').on('change', function () { file = this.files[0]; $('#StatusMessage').html("File Size in bytes: " + file.size).show(); }); $('#inputForm').on('submit', function (e) { e.preventDefault(); if (!file || file.size < 1) { alert('Specified file is not valid'); return; } var onComplete = function () { $('#StatusMessage').html('').hide(); file = null; $('#inputForm').show(); }; $('#StatusMessage').html('
    ' + '
    ' + '
    ').show(); $('#inputForm').hide(); var bitRate = parseInt($('#bitRate').val(), 10); converter.convert(file, { bitRate: bitRate }, function (blob) { var blobUrl = window.URL.createObjectURL(blob); $('ol.convertedList') .append('
  • ' + file.name + '
    ' + '' + '
  • '); onComplete(); }, function (progress) { $('#StatusMessage') .find('.progress-bar') .css('width', (progress * 100) + '%'); }); }); }); ``` -------------------------------- ### Real-time Microphone Recording to MP3 with JavaScript Source: https://context7.com/gideonstele/lamejs/llms.txt Captures microphone input using the Web Audio API and encodes it to MP3 in real-time using lamejs. This snippet includes starting and stopping the recording, processing audio samples, and creating a downloadable MP3 blob. It requires user permission for microphone access. ```javascript import { Mp3Encoder } from '@breezystack/lamejs'; class MP3Recorder { constructor(config = {}) { this.config = config; this.audioContext = new AudioContext(); this.mp3Encoder = null; this.dataBuffer = []; this.recording = false; } async start() { // Request microphone access const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); // Initialize encoder with audio context sample rate const sampleRate = this.audioContext.sampleRate; const bitRate = this.config.bitRate || 128; this.mp3Encoder = new Mp3Encoder(1, sampleRate, bitRate); this.dataBuffer = []; // Create audio processing pipeline const microphone = this.audioContext.createMediaStreamSource(stream); const processor = this.audioContext.createScriptProcessor(4096, 1, 1); processor.onaudioprocess = (e) => { if (!this.recording) return; // Get audio samples from microphone const samples = e.inputBuffer.getChannelData(0); // Convert Float32Array to Int16Array const int16Samples = new Int16Array(samples.length); for (let i = 0; i < samples.length; i++) { const s = Math.max(-1, Math.min(1, samples[i])); int16Samples[i] = s < 0 ? s * 0x8000 : s * 0x7FFF; } // Encode to MP3 const mp3buf = this.mp3Encoder.encodeBuffer(int16Samples); if (mp3buf.length > 0) { this.dataBuffer.push(mp3buf); } }; microphone.connect(processor); processor.connect(this.audioContext.destination); this.recording = true; this.microphone = microphone; this.processor = processor; this.stream = stream; } stop() { this.recording = false; if (this.microphone) { this.microphone.disconnect(); this.processor.disconnect(); } if (this.stream) { this.stream.getTracks().forEach(track => track.stop()); } // Flush encoder const finalBuf = this.mp3Encoder.flush(); if (finalBuf.length > 0) { this.dataBuffer.push(finalBuf); } // Create MP3 blob const mp3Blob = new Blob(this.dataBuffer, { type: 'audio/mp3' }); return mp3Blob; } } // Usage const recorder = new MP3Recorder({ bitRate: 128 }); document.getElementById('startBtn').addEventListener('click', async () => { await recorder.start(); console.log('Recording started...'); }); document.getElementById('stopBtn').addEventListener('click', () => { const mp3Blob = recorder.stop(); console.log('Recording stopped. MP3 size:', mp3Blob.size, 'bytes'); // Download the recording const url = URL.createObjectURL(mp3Blob); const a = document.createElement('a'); a.href = url; a.download = 'recording.mp3'; a.click(); }); ``` -------------------------------- ### Initialize Mp3Encoder Instance Source: https://context7.com/gideonstele/lamejs/llms.txt Initializes a new Mp3Encoder with specified audio parameters. Supports mono and stereo configurations, sample rates, and bitrates for PCM audio encoding. ```javascript import { Mp3Encoder } from '@breezystack/lamejs'; // Create encoder for mono audio at 44.1kHz with 128kbps bitrate const encoder = new Mp3Encoder(1, 44100, 128); // Create encoder for stereo audio at 48kHz with 192kbps bitrate const stereoEncoder = new Mp3Encoder(2, 48000, 192); ``` -------------------------------- ### WAV to MP3 Conversion using Web Workers in JavaScript Source: https://context7.com/gideonstele/lamejs/llms.txt This snippet showcases the client-side logic for converting WAV audio files to MP3 format. It involves a Web Worker (`worker.js`) for encoding and a main script (`main.js`) to handle file reading, worker communication, and downloading the resulting MP3. The worker script decodes WAV headers, extracts audio samples, encodes them using lamejs, and sends the MP3 data back to the main thread. The main script then creates a Blob and initiates a download. It depends on the `lamejs.iife.js` library. ```javascript // worker.js importScripts('lamejs.iife.js'); let mp3Encoder, dataBuffer = []; self.onmessage = function(e) { switch (e.data.cmd) { case 'init': dataBuffer = []; break; case 'encode': const wav = lamejs.WavHeader.readHeader(new DataView(e.data.rawInput)); if (!wav) { self.postMessage({ cmd: 'error', msg: 'Invalid WAV file' }); return; } // Extract samples const dataView = new Int16Array(e.data.rawInput, wav.dataOffset, wav.dataLen / 2); const samplesLeft = wav.channels === 1 ? dataView : new Int16Array(wav.dataLen / (2 * wav.channels)); const samplesRight = wav.channels === 2 ? new Int16Array(wav.dataLen / (2 * wav.channels)) : undefined; // Deinterleave stereo if (wav.channels > 1) { for (let i = 0; i < samplesLeft.length; i++) { samplesLeft[i] = dataView[i * 2]; samplesRight[i] = dataView[i * 2 + 1]; } } // Initialize encoder mp3Encoder = new lamejs.Mp3Encoder(wav.channels, wav.sampleRate, 128); // Encode chunks const maxSamples = 1152; let remaining = samplesLeft.length; for (let i = 0; remaining >= maxSamples; i += maxSamples) { const left = samplesLeft.subarray(i, i + maxSamples); const right = samplesRight ? samplesRight.subarray(i, i + maxSamples) : undefined; const mp3buf = mp3Encoder.encodeBuffer(left, right); dataBuffer.push(new Int8Array(mp3buf)); remaining -= maxSamples; self.postMessage({ cmd: 'progress', progress: 1 - remaining / samplesLeft.length }); } break; case 'finish': const finalBuf = mp3Encoder.flush(); dataBuffer.push(new Int8Array(finalBuf)); self.postMessage({ cmd: 'end', buf: dataBuffer }); dataBuffer = []; break; } }; // main.js const worker = new Worker('worker.js'); function convertFile(file) { const reader = new FileReader(); reader.onload = function(e) { worker.postMessage({ cmd: 'init' }); worker.postMessage({ cmd: 'encode', rawInput: e.target.result }); worker.postMessage({ cmd: 'finish' }); }; worker.onmessage = function(e) { if (e.data.cmd === 'end') { const mp3Blob = new Blob(e.data.buf, { type: 'audio/mp3' }); const url = URL.createObjectURL(mp3Blob); const a = document.createElement('a'); a.href = url; a.download = 'output.mp3'; a.click(); } else if (e.data.cmd === 'progress') { console.log('Progress:', Math.round(e.data.progress * 100) + '%'); } }; reader.readAsArrayBuffer(file); } // Usage with file input document.getElementById('fileInput').addEventListener('change', (e) => { convertFile(e.target.files[0]); }); ``` -------------------------------- ### Mp3Encoder Constructor Source: https://context7.com/gideonstele/lamejs/llms.txt Initializes a new Mp3Encoder instance with specified audio parameters for encoding PCM audio data to MP3 format. Supports mono and stereo encoding with configurable bitrates and sample rates. ```APIDOC ## Mp3Encoder Constructor ### Description Initialize a new MP3 encoder instance with specified audio parameters for encoding PCM audio data to MP3 format. ### Method `new Mp3Encoder(channels, sampleRate, kbps)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **channels** (number) - Required - The number of audio channels (1 for mono, 2 for stereo). * **sampleRate** (number) - Required - The audio sample rate in Hz (e.g., 44100, 48000). * **kbps** (number) - Required - The desired bitrate in kilobits per second (e.g., 128, 192). ### Request Example ```javascript import { Mp3Encoder } from '@breezystack/lamejs'; // Create encoder for mono audio at 44.1kHz with 128kbps bitrate const encoder = new Mp3Encoder(1, 44100, 128); // Create encoder for stereo audio at 48kHz with 192kbps bitrate const stereoEncoder = new Mp3Encoder(2, 48000, 192); ``` ### Response #### Success Response (200) An instance of the `Mp3Encoder` class. #### Response Example ```javascript // encoder instance ``` ``` -------------------------------- ### Complete WAV to MP3 Conversion in Node.js using LameJS Source: https://context7.com/gideonstele/lamejs/llms.txt Converts an entire WAV file to MP3 format using Node.js. It reads the WAV file, parses its header, and then processes the audio data in chunks using the Mp3Encoder. The resulting MP3 data is written to an output file. Dependencies include 'fs' for file operations and '@breezystack/lamejs' for WAV header parsing and MP3 encoding. ```javascript import fs from 'fs'; import { WavHeader, Mp3Encoder } from '@breezystack/lamejs'; function convertWavToMp3(inputPath, outputPath) { // Read WAV file const wavBuffer = fs.readFileSync(inputPath); const arrayBuffer = new Uint8Array(wavBuffer).buffer; // Parse WAV header const wav = WavHeader.readHeader(new DataView(arrayBuffer)); const samples = new Int16Array(arrayBuffer, wav.dataOffset, wav.dataLen / 2); // Initialize encoder const encoder = new Mp3Encoder(wav.channels, wav.sampleRate, 128); const maxSamples = 1152; // Open output file const fd = fs.openSync(outputPath, 'w'); // Process audio in chunks let remaining = samples.length; for (let i = 0; remaining >= maxSamples; i += maxSamples) { const left = samples.subarray(i, i + maxSamples); const right = wav.channels === 2 ? samples.subarray(i, i + maxSamples) : left; const mp3buf = encoder.encodeBuffer(left, right); if (mp3buf.length > 0) { fs.writeSync(fd, Buffer.from(mp3buf.buffer), 0, mp3buf.length); } remaining -= maxSamples; } // Flush and finalize const finalBuffer = encoder.flush(); if (finalBuffer.length > 0) { fs.writeSync(fd, Buffer.from(finalBuffer.buffer), 0, finalBuffer.length); } fs.closeSync(fd); console.log('Conversion complete:', outputPath); } convertWavToMp3('input.wav', 'output.mp3'); ``` -------------------------------- ### WavHeader.readHeader() Source: https://context7.com/gideonstele/lamejs/llms.txt Parses a WAV file header from a DataView to extract audio format parameters such as channels, sample rate, data offset, and data length. ```APIDOC ## WavHeader.readHeader() ### Description Parse WAV file header information to extract audio format parameters needed for MP3 encoding. ### Method `WavHeader.readHeader(dataView)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **dataView** (DataView) - Required - A DataView object representing the binary data of the WAV file. ### Request Example ```javascript import { WavHeader, Mp3Encoder } from '@breezystack/lamejs'; // Node.js example import fs from 'fs'; const wavFile = fs.readFileSync('audio.wav'); const arrayBuffer = new Uint8Array(wavFile).buffer; const wavHeader = WavHeader.readHeader(new DataView(arrayBuffer)); console.log('Channels:', wavHeader.channels); console.log('Sample rate:', wavHeader.sampleRate); console.log('Data offset:', wavHeader.dataOffset); console.log('Data length:', wavHeader.dataLen); // Extract PCM samples from WAV file const samples = new Int16Array(arrayBuffer, wavHeader.dataOffset, wavHeader.dataLen / 2); // Create encoder matching WAV format const encoder = new Mp3Encoder(wavHeader.channels, wavHeader.sampleRate, 128); ``` ### Response #### Success Response (200) - **WavHeader object** - An object containing WAV header information: * **channels** (number) - The number of audio channels. * **sampleRate** (number) - The sample rate in Hz. * **dataOffset** (number) - The byte offset to the start of the audio data. * **dataLen** (number) - The total length of the audio data in bytes. #### Response Example ```javascript { "channels": 2, "sampleRate": 44100, "dataOffset": 44, "dataLen": 176400 } ``` ``` -------------------------------- ### Convert WAV to MP3 in Node.js using CommonJS Source: https://context7.com/gideonstele/lamejs/llms.txt This snippet demonstrates how to use lamejs to convert WAV audio files to MP3 format within a Node.js environment using CommonJS modules. It reads WAV data, processes it through the Mp3Encoder, and writes the resulting MP3 file. Dependencies include the 'fs' and 'path' modules. ```javascript const { Mp3Encoder, WavHeader } = require('@breezystack/lamejs'); const fs = require('fs'); const path = require('path'); function convertWavFile(inputFile, outputFile) { const wavData = fs.readFileSync(inputFile); const buffer = new Uint8Array(wavData).buffer; const wav = WavHeader.readHeader(new DataView(buffer)); if (!wav) { throw new Error('Invalid WAV file'); } const samples = new Int16Array(buffer, wav.dataOffset, wav.dataLen / 2); const encoder = new Mp3Encoder(wav.channels, wav.sampleRate, 128); const chunks = []; const maxSamples = 1152; for (let i = 0; i < samples.length; i += maxSamples) { const chunk = samples.subarray(i, Math.min(i + maxSamples, samples.length)); const mp3Buf = encoder.encodeBuffer(chunk); if (mp3Buf.length > 0) { chunks.push(Buffer.from(mp3Buf.buffer)); } } const finalBuf = encoder.flush(); if (finalBuf.length > 0) { chunks.push(Buffer.from(finalBuf.buffer)); } fs.writeFileSync(outputFile, Buffer.concat(chunks)); console.log('Converted:', outputFile); } // Batch process multiple files const inputDir = './wav-files'; const outputDir = './mp3-files'; fs.readdirSync(inputDir) .filter(file => file.endsWith('.wav')) .forEach(file => { const inputPath = path.join(inputDir, file); const outputPath = path.join(outputDir, file.replace('.wav', '.mp3')); convertWavFile(inputPath, outputPath); }); ``` -------------------------------- ### Import Lamejs in Node.js or bundler (CommonJS) Source: https://github.com/gideonstele/lamejs/blob/master/README.md Shows how to import the lamejs library using CommonJS syntax, which is compatible with older Node.js versions or projects that do not use ES Modules. ```javascript const lame = require('@breezystack/lamejs'); ``` -------------------------------- ### Mp3Encoder.encodeBuffer() Source: https://context7.com/gideonstele/lamejs/llms.txt Encodes a chunk of PCM audio samples into MP3 format. Accepts separate Int16Array for left and right channels for stereo, or a single array for mono. ```APIDOC ## Mp3Encoder.encodeBuffer() ### Description Encode a chunk of PCM audio samples into MP3 format, processing left and right channels for stereo or a single channel for mono. ### Method `encodeBuffer(leftChannel, rightChannel?)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **leftChannel** (Int16Array) - Required - An array of 16-bit PCM samples for the left channel. * **rightChannel** (Int16Array) - Optional - An array of 16-bit PCM samples for the right channel. If omitted, mono encoding is performed using only `leftChannel`. ### Request Example ```javascript import { Mp3Encoder } from '@breezystack/lamejs'; const channels = 2; const sampleRate = 44100; const kbps = 128; const encoder = new Mp3Encoder(channels, sampleRate, kbps); // Stereo encoding with separate left and right channels const samplesPerFrame = 1152; // Standard MP3 frame size const leftChannel = new Int16Array(samplesPerFrame); const rightChannel = new Int16Array(samplesPerFrame); // Fill with audio data (example: simple sine waves) for (let i = 0; i < samplesPerFrame; i++) { leftChannel[i] = Math.floor(Math.sin(2 * Math.PI * 440 * i / sampleRate) * 32767); rightChannel[i] = Math.floor(Math.sin(2 * Math.PI * 880 * i / sampleRate) * 32767); } // Encode and get MP3 data chunk const mp3Data = encoder.encodeBuffer(leftChannel, rightChannel); console.log('Encoded MP3 chunk size:', mp3Data.length, 'bytes'); // For mono encoding, only pass left channel const monoEncoder = new Mp3Encoder(1, 44100, 96); const monoData = monoEncoder.encodeBuffer(leftChannel); ``` ### Response #### Success Response (200) - **mp3Data** (Uint8Array) - A Uint8Array containing the encoded MP3 data for the processed chunk. #### Response Example ```javascript // mp3Data: Uint8Array([255, 241, 224, 0, ...]) ``` ``` -------------------------------- ### Stereo WAV to MP3 Conversion with Separate Channels in Node.js using LameJS Source: https://context7.com/gideonstele/lamejs/llms.txt Encodes stereo audio from two separate WAV files (left and right channels) into a single MP3 file. It reads both WAV files, parses their headers, verifies sample rate compatibility, and then encodes the audio data in chunks. The function ensures that the output MP3 file contains stereo audio. Dependencies include 'fs' for file operations and '@breezystack/lamejs' for WAV header parsing and MP3 encoding. ```javascript import fs from 'fs'; import { WavHeader, Mp3Encoder } from '@breezystack/lamejs'; function convertStereoToMp3(leftWavPath, rightWavPath, outputPath) { // Read both WAV files const leftBuffer = new Uint8Array(fs.readFileSync(leftWavPath)).buffer; const rightBuffer = new Uint8Array(fs.readFileSync(rightWavPath)).buffer; // Parse headers const leftWav = WavHeader.readHeader(new DataView(leftBuffer)); const rightWav = WavHeader.readHeader(new DataView(rightBuffer)); // Verify compatibility if (leftWav.sampleRate !== rightWav.sampleRate) { throw new Error('Sample rates must match'); } // Extract samples const leftSamples = new Int16Array(leftBuffer, leftWav.dataOffset, leftWav.dataLen / 2); const rightSamples = new Int16Array(rightBuffer, rightWav.dataOffset, rightWav.dataLen / 2); // Create stereo encoder const encoder = new Mp3Encoder(2, leftWav.sampleRate, 128); const maxSamples = 1152; const fd = fs.openSync(outputPath, 'w'); // Encode in chunks let remaining = Math.min(leftSamples.length, rightSamples.length); for (let i = 0; remaining >= maxSamples; i += maxSamples) { const left = leftSamples.subarray(i, i + maxSamples); const right = rightSamples.subarray(i, i + maxSamples); const mp3buf = encoder.encodeBuffer(left, right); if (mp3buf.length > 0) { fs.writeSync(fd, Buffer.from(mp3buf.buffer), 0, mp3buf.length); } remaining -= maxSamples; } // Finalize const finalBuf = encoder.flush(); if (finalBuf.length > 0) { fs.writeSync(fd, Buffer.from(finalBuf.buffer), 0, finalBuf.length); } fs.closeSync(fd); console.log('Stereo MP3 created:', outputPath); } convertStereoToMp3('left.wav', 'right.wav', 'stereo.mp3'); ``` -------------------------------- ### Import Lamejs in Node.js or bundler (ES Module) Source: https://github.com/gideonstele/lamejs/blob/master/README.md Demonstrates how to import the lamejs library using ES Module syntax, suitable for Node.js environments or projects utilizing bundlers like Webpack or Rollup. ```javascript import * as lame from '@breezystack/lamejs'; ``` -------------------------------- ### Encode PCM Audio Buffer to MP3 Source: https://context7.com/gideonstele/lamejs/llms.txt Encodes a chunk of PCM audio samples into MP3 format. Handles both stereo (left/right channels) and mono audio inputs. Returns an ArrayBuffer containing the MP3 data. ```javascript import { Mp3Encoder } from '@breezystack/lamejs'; const channels = 2; const sampleRate = 44100; const kbps = 128; const encoder = new Mp3Encoder(channels, sampleRate, kbps); // Stereo encoding with separate left and right channels const samplesPerFrame = 1152; // Standard MP3 frame size const leftChannel = new Int16Array(samplesPerFrame); const rightChannel = new Int16Array(samplesPerFrame); // Fill with audio data (example: simple sine waves) for (let i = 0; i < samplesPerFrame; i++) { leftChannel[i] = Math.floor(Math.sin(2 * Math.PI * 440 * i / sampleRate) * 32767); rightChannel[i] = Math.floor(Math.sin(2 * Math.PI * 880 * i / sampleRate) * 32767); } // Encode and get MP3 data chunk const mp3Data = encoder.encodeBuffer(leftChannel, rightChannel); console.log('Encoded MP3 chunk size:', mp3Data.length, 'bytes'); // For mono encoding, only pass left channel const monoEncoder = new Mp3Encoder(1, 44100, 96); const monoData = monoEncoder.encodeBuffer(leftChannel); ``` -------------------------------- ### Include Lamejs using ES Module script tag Source: https://github.com/gideonstele/lamejs/blob/master/README.md Demonstrates how to include the lamejs library in an HTML document as an ES Module, allowing for modern module loading practices. ```html ``` -------------------------------- ### Parse WAV File Header Source: https://context7.com/gideonstele/lamejs/llms.txt Reads and parses the header of a WAV audio file to extract essential audio format parameters like channel count, sample rate, data offset, and data length. This information is used to configure the Mp3Encoder correctly. ```javascript import { WavHeader, Mp3Encoder } from '@breezystack/lamejs'; // Node.js example import fs from 'fs'; const wavFile = fs.readFileSync('audio.wav'); const arrayBuffer = new Uint8Array(wavFile).buffer; const wavHeader = WavHeader.readHeader(new DataView(arrayBuffer)); console.log('Channels:', wavHeader.channels); console.log('Sample rate:', wavHeader.sampleRate); console.log('Data offset:', wavHeader.dataOffset); console.log('Data length:', wavHeader.dataLen); // Extract PCM samples from WAV file const samples = new Int16Array(arrayBuffer, wavHeader.dataOffset, wavHeader.dataLen / 2); // Create encoder matching WAV format const encoder = new Mp3Encoder(wavHeader.channels, wavHeader.sampleRate, 128); ``` -------------------------------- ### Mp3Encoder.flush() Source: https://context7.com/gideonstele/lamejs/llms.txt Finalizes the MP3 encoding process and retrieves any remaining buffered MP3 data. This should be called after all audio chunks have been encoded. ```APIDOC ## Mp3Encoder.flush() ### Description Finalize the encoding process and retrieve any remaining MP3 data in the encoder's internal buffer. ### Method `flush()` ### Parameters None ### Request Example ```javascript import { Mp3Encoder } from '@breezystack/lamejs'; const encoder = new Mp3Encoder(1, 44100, 128); const mp3Chunks = []; // Encode multiple chunks of audio const samples = new Int16Array(5000); for (let i = 0; i < samples.length; i += 1152) { const chunk = samples.subarray(i, Math.min(i + 1152, samples.length)); const mp3Buf = encoder.encodeBuffer(chunk); if (mp3Buf.length > 0) { mp3Chunks.push(mp3Buf); } } // Flush remaining data and finalize const remainingData = encoder.flush(); if (remainingData.length > 0) { mp3Chunks.push(remainingData); } // Create final MP3 blob const mp3Blob = new Blob(mp3Chunks, { type: 'audio/mp3' }); console.log('Final MP3 size:', mp3Blob.size, 'bytes'); ``` ### Response #### Success Response (200) - **remainingData** (Uint8Array) - A Uint8Array containing any remaining MP3 data from the encoder's buffer. #### Response Example ```javascript // remainingData: Uint8Array([...]) ``` ``` -------------------------------- ### Include Lamejs using IIFE script tag Source: https://github.com/gideonstele/lamejs/blob/master/README.md Illustrates how to include the lamejs library in an HTML document using an Immediately Invoked Function Expression (IIFE) script tag, making the library available globally. ```html ``` -------------------------------- ### Flush Remaining MP3 Data Source: https://context7.com/gideonstele/lamejs/llms.txt Finalizes the MP3 encoding process and retrieves any remaining data buffered by the encoder. This is crucial for completing the MP3 file, especially after encoding multiple chunks. ```javascript import { Mp3Encoder } from '@breezystack/lamejs'; const encoder = new Mp3Encoder(1, 44100, 128); const mp3Chunks = []; // Encode multiple chunks of audio const samples = new Int16Array(5000); for (let i = 0; i < samples.length; i += 1152) { const chunk = samples.subarray(i, Math.min(i + 1152, samples.length)); const mp3Buf = encoder.encodeBuffer(chunk); if (mp3Buf.length > 0) { mp3Chunks.push(mp3Buf); } } // Flush remaining data and finalize const remainingData = encoder.flush(); if (remainingData.length > 0) { mp3Chunks.push(remainingData); } // Create final MP3 blob const mp3Blob = new Blob(mp3Chunks, { type: 'audio/mp3' }); console.log('Final MP3 size:', mp3Blob.size, 'bytes'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.