LAME MP3 Encoder Bindings

1.8.2 · active · verified Sat Apr 11

lameenc is a Python library providing bindings for the LAME MP3 encoding library. It simplifies the process of encoding PCM audio data into MP3 format without requiring users to compile the LAME binaries themselves, as it distributes pre-compiled wheels for various operating systems and Python versions. The library is actively maintained, with frequent updates to support new Python versions and add features.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `lameenc.Encoder`, configure its parameters like bit rate, sample rate, channels, and quality, and then encode raw 16-bit interleaved PCM audio data into an MP3 byte stream. The example includes generating dummy stereo sine wave PCM data for a runnable demonstration.

import lameenc
import array

# Example: Generate some dummy 16-bit PCM stereo audio (e.g., a sine wave)
# For a real application, this would come from an audio input/file
sample_rate = 44100  # Hz
channels = 2         # Stereo
duration = 3         # seconds
num_samples = sample_rate * duration

# Create a bytearray for 16-bit interleaved PCM data
# Each sample is 2 bytes (16-bit), stereo means 2 samples per frame
pcm_data_raw = array.array('h', [0] * (num_samples * channels))

# Fill with a simple sine wave (for demonstration purposes)
import math
for i in range(num_samples):
    amplitude = int(32767 * math.sin(2 * math.pi * 440 * i / sample_rate))
    pcm_data_raw[i * channels] = amplitude  # Left channel
    pcm_data_raw[i * channels + 1] = amplitude # Right channel

pcm_bytes = pcm_data_raw.tobytes()

# Initialize the encoder
encoder = lameenc.Encoder()
encoder.set_bit_rate(128)  # 128 kbps
encoder.set_in_sample_rate(sample_rate)
encoder.set_channels(channels)
encoder.set_quality(2)     # 2 = highest, 7 = fastest

# Encode the audio
mp3_data = encoder.encode(pcm_bytes)
mp3_data += encoder.flush() # Flush any remaining buffered data

# Save to a file (optional)
with open('output.mp3', 'wb') as f:
    f.write(mp3_data)

print(f"MP3 data generated and saved to output.mp3 (size: {len(mp3_data)} bytes)")

view raw JSON →