pymp3 Library

0.2.0 · active · verified Thu Apr 16

pymp3 is a lightweight Python library for reading and writing MP3 files, primarily providing low-level access to MP3 frames and PCM data. It is currently at version 0.2.0 and has an infrequent release cadence, focusing on stability and essential bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `pymp3.MP3Decoder` to process MP3 data into PCM frames. It also includes a conceptual example for `MP3Encoder`. For actual use, replace the placeholder `mp3_data` with valid MP3 content from a file or stream. The library provides low-level access to audio frames, not high-level ID3 tag manipulation.

import io
from pymp3 import MP3Decoder

# In a real application, mp3_data would come from a file or network stream
# For demonstration, we'll use a placeholder or minimal real data if available.
# Note: A real MP3 file's header is required for successful decoding.
# This example uses a very small, non-functional byte string as a stand-in
# to illustrate the API without requiring a file. Expect decoding errors with this.
# Replace with actual MP3 data for practical use.

# Example of dummy data (will likely fail to decode, but shows API):
mp3_data = b'\xff\xfb\x90\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

try:
    decoder = MP3Decoder()
    frames = decoder.decode(mp3_data)

    if not frames:
        print("No frames decoded. Ensure 'mp3_data' contains valid MP3 content.")
    else:
        print(f"Decoded {len(frames)} PCM frames.")
        for i, frame in enumerate(frames):
            if i < 3: # Print details for first few frames
                print(f"Frame {i+1}: Sample Rate={frame.sample_rate}Hz, Channels={frame.channels}, Data Size={frame.data_size} bytes")
            # frame.data contains the raw PCM bytes

except Exception as e:
    print(f"An error occurred during decoding: {e}")
    print("HINT: Ensure the 'mp3_data' variable contains actual, valid MP3 audio data.")


# --- Example of encoding (conceptual, requires PCM data) ---
# from pymp3 import MP3Encoder, PCMFrame
#
# # Assuming you have some PCM data (e.g., from decoding or generation)
# # This is highly conceptual as valid PCM data is required.
# dummy_pcm_data = b'\x00\x00\x00\x00' * 1024 # Placeholder 16-bit stereo silence
# sample_rate = 44100
# channels = 2
# pcm_frame = PCMFrame(sample_rate, channels, dummy_pcm_data)
#
# try:
#     encoder = MP3Encoder(sample_rate=sample_rate, channels=channels, bitrate=128)
#     encoded_mp3_data = encoder.encode([pcm_frame]) # encode expects a list of frames
#     print(f"Encoded {len(encoded_mp3_data)} bytes of MP3 data (conceptual).")
# except Exception as e:
#     print(f"An error occurred during encoding: {e}")
#     print("HINT: Ensure PCMFrame data and encoder parameters are valid.")

view raw JSON →