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, ormemoryview.On success, this method returns a 5-tuple:
(bytes_used, pcm_data, channels, samplerate, bitrate)
The tuple values are:
bytes_usedNumber of compressed input bytes consumed by the decoder.
pcm_dataDecoded PCM data as a
bytesobject.channelsNumber of audio channels.
Common values are:
1for mono2for stereo
samplerateAudio sample rate in Hz.
For example,
44100.bitrateMP3 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_usedmay 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
Noneis returned.The volume value is clamped to the range
0to100.Example:
dec.volume(50) # Set volume to 50 current = dec.volume() # Get current volume
Volume behavior:
0sets the output near silent.100keeps the original decoded PCM level.values between
1and99apply 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()