mp3 — MP3 decoder

This module provides an MP3 decoder interface. It can decode compressed MP3 data into PCM audio data.

The mp3 module currently provides the Decoder class.

MP3 decoder class

class mp3.Decoder

Create a new MP3 decoder object.

Example:

import mp3

dec = mp3.Decoder()

The decoder object provides methods to decode MP3 data, control playback volume, and release decoder resources.

Methods

Decoder.decode(buffer)

Decode MP3 data from buffer.

The buffer argument must be an object that supports the buffer protocol, such as bytes, bytearray, or memoryview.

On success, this method returns a 5-tuple:

(bytes_used, pcm_data, channels, samplerate, bitrate)

The tuple values are:

bytes_used

Number of compressed input bytes consumed by the decoder.

pcm_data

Decoded PCM data as a bytes object.

channels

Number of audio channels.

Common values are:

  • 1 for mono

  • 2 for stereo

samplerate

Audio sample rate in Hz.

For example, 44100.

bitrate

MP3 bitrate value returned by the decoder.

If the decoder cannot find a valid MP3 sync word or does not have enough data to decode a full frame, it returns an empty PCM bytes object in the tuple.

Example:

res = dec.decode(buffer_view)

bytes_used, pcm_data, channels, samplerate, bitrate = res

if bytes_used > 0 and len(pcm_data) > 0:
    print("PCM length:", len(pcm_data))
    print("channels:", channels)
    print("samplerate:", samplerate)

Note

The current implementation returns a 5-tuple for normal decode handling. For serious decoder errors, bytes_used may contain a negative error value.

Decoder.volume([level])

Get or set the decoder output volume.

If level is not provided, the current volume is returned.

If level is provided, the decoder volume is set and None is returned.

The volume value is clamped to the range 0 to 100.

Example:

dec.volume(50)       # Set volume to 50
current = dec.volume()   # Get current volume

Volume behavior:

  • 0 sets the output near silent.

  • 100 keeps the original decoded PCM level.

  • values between 1 and 99 apply volume scaling.

Decoder.deinit()

Release resources used by the decoder.

This should be called when playback is finished or when the decoder is no longer required.

Example:

dec.deinit()

Example

The following example shows the basic decoder usage pattern. It does not include I2S playback.

Example:

import mp3

dec = mp3.Decoder()
dec.volume(50)

in_buffer = bytearray(4096)

try:
    with open("/sd/test.mp3", "rb") as f:
        n = f.readinto(in_buffer)
        buffer_view = memoryview(in_buffer)[:n]

        res = dec.decode(buffer_view)

        bytes_used, pcm_data, channels, samplerate, bitrate = res

        print("bytes_used:", bytes_used)
        print("pcm_len:", len(pcm_data))
        print("channels:", channels)
        print("samplerate:", samplerate)
        print("bitrate:", bitrate)

finally:
    dec.deinit()