Multiplatform audio playback, recording, decoding and sample format conversion for
Linux (including Raspberry Pi), Windows, Mac and others.
Installation for most users: via Pypi, Raspberry Pi builds via PiWheels.
This is a Pythonic interface to the cross-platform miniaudio C library:
audio operations run in the background
python bindings for most of the functions offered in the miniaudio library:
reading and decoding audio files
getting audio file properties (such as duration, number of channels, sample rate)
converting sample formats and frequencies
streaming large audio files
audio playback
audio recording
decoders for wav, flac, vorbis and mp3
Audio file and Icecast internet radio streaming
Python enums instead of just some integers for special values
several classes to represent the main functions of the library
generators for the Audio playback and recording
sample data is usually in the form of a Python array with appropriately sized elements
depending on the sample width (rather than a raw block of bytes)
TODO: migrate deprecated ma_stop_proc/stopCallback usage to ma_device_notification_proc/notificationCallback for more reliable device state and reroute handling.
Requires Python 3.11 or newer. Also works on pypy3 (because it uses cffi).
The miniaudio C library version is 0.11.26.
Software license for these Python bindings, miniaudio and the decoders: MIT
import miniaudio
# Get file info
info = miniaudio.get_file_info("samples/music.mp3")
print(f"Playing: {info.nchannels} channels, {info.sample_rate} Hz, {info.duration:.1f}s")
# Stream and play
stream = miniaudio.stream_file("samples/music.mp3")
with miniaudio.PlaybackDevice() as device:
device.start(stream)
input("Playing... press Enter to stop")
Decode and convert audio file
import miniaudio
# Decode audio file to float32
sound = miniaudio.decode_file("music.mp3", miniaudio.SampleFormat.FLOAT32)
print(f"Decoded: {sound.nchannels} ch, {sound.sample_rate} Hz, {sound.num_frames} frames")
# Convert to different format and sample rate
converted = miniaudio.convert_frames(
sound.sample_format, sound.nchannels, sound.sample_rate,
sound.samples.tobytes(),
miniaudio.SampleFormat.SIGNED16, sound.nchannels, 22050
)
# Write to WAV file
miniaudio.wav_write_file("output.wav", miniaudio.DecodedSoundFile(
"output.wav", sound.nchannels, 22050, miniaudio.SampleFormat.SIGNED16,
converted
))
print("Written to output.wav")
Playback of an unsupported file format
This example uses ffmpeg as an external tool to decode an audio file in a format
that miniaudio itself can't decode (m4a/aac in this case):
import subprocess
import miniaudio
channels = 2
sample_rate = 44100
sample_width = 2 # 16 bit pcm
filename = "samples/music.m4a" # AAC encoded audio file
def stream_pcm(source):
required_frames = yield b"" # generator initialization
while True:
required_bytes = required_frames * channels * sample_width
sample_data = source.read(required_bytes)
if not sample_data:
break
print(".", end="", flush=True)
required_frames = yield sample_data
with miniaudio.PlaybackDevice(output_format=miniaudio.SampleFormat.SIGNED16,
nchannels=channels, sample_rate=sample_rate) as device:
ffmpeg = subprocess.Popen(["ffmpeg", "-v", "fatal", "-hide_banner", "-nostdin",
"-i", filename, "-f", "s16le", "-acodec", "pcm_s16le",
"-ac", str(channels), "-ar", str(sample_rate), "-"],
stdin=None, stdout=subprocess.PIPE)
stream = stream_pcm(ffmpeg.stdout)
next(stream) # start the generator
device.start(stream)
input("Audio file playing in the background. Enter to stop playback: ")
ffmpeg.terminate()
API
Note: everything below is automatically generated from comments in the source code files. Do not edit in this readme directly.
Convert audio frames in source sample format with a certain number of channels, to another sample
format and possibly down/upmixing the number of channels as well.
Reads and decodes the whole flac audio data. Resulting sample format is 32 bits signed integer.
functionflac_stream_file (filename: str, frames_to_read: int = 1024, seek_frame: int = 0) -> Generator[array.array, NoneType, NoneType]
Streams the flac audio file as interleaved 16 bit signed integer sample arrays segments. This uses
a fixed chunk size and cannot be used as a generic miniaudio decoder input stream. Consider using
stream_file() instead.
Reads and decodes the whole mp3 audio data. Resulting sample format is 16 bits signed integer.
functionmp3_stream_file (filename: str, frames_to_read: int = 1024, seek_frame: int = 0) -> Generator[array.array, NoneType, NoneType]
Streams the mp3 audio file as interleaved 16 bit signed integer sample arrays segments. This uses
a fixed chunk size and cannot be used as a generic miniaudio decoder input stream. Consider using
stream_file() instead.
Reads and decodes the whole audio file. Miniaudio will attempt to return the sound data in exactly
the same format as in the file. Unless you set convert_convert_to_16bit to True, then the result is
always a 16 bit sample format.
functionstream_any (source: miniaudio.StreamableSource, source_format: miniaudio.FileFormat = <FileFormat.UNKNOWN: 0>, output_format: miniaudio.SampleFormat = <SampleFormat.SIGNED16: 2>, nchannels: int = 2, sample_rate: int = 44100, frames_to_read: int = 1024, dither: miniaudio.DitherMode = <DitherMode.NONE: 0>, seek_frame: int = 0) -> Generator[array.array, int, NoneType]
Convenience function that returns a generator to decode and stream any source of encoded audio
data (such as a network stream). Stream result is chunks of raw PCM samples in the chosen format. If
you send() a number into the generator rather than just using next() on it, you'll get that given
number of frames, instead of the default configured amount. This is particularly useful to plug this
stream into an audio device callback that wants a variable number of frames per call.
functionstream_file (filename: str, output_format: miniaudio.SampleFormat = <SampleFormat.SIGNED16: 2>, nchannels: int = 2, sample_rate: int = 44100, frames_to_read: int = 1024, dither: miniaudio.DitherMode = <DitherMode.NONE: 0>, seek_frame: int = 0) -> Generator[array.array, int, NoneType]
Convenience generator function to decode and stream any supported audio file as chunks of raw PCM
samples in the chosen format. If you send() a number into the generator rather than just using
next() on it, you'll get that given number of frames, instead of the default configured amount. This
is particularly useful to plug this stream into an audio device callback that wants a variable
number of frames per call.
functionstream_memory (data: bytes, output_format: miniaudio.SampleFormat = <SampleFormat.SIGNED16: 2>, nchannels: int = 2, sample_rate: int = 44100, frames_to_read: int = 1024, dither: miniaudio.DitherMode = <DitherMode.NONE: 0>) -> Generator[array.array, int, NoneType]
Convenience generator function to decode and stream any supported audio file in memory as chunks
of raw PCM samples in the chosen format. If you send() a number into the generator rather than just
using next() on it, you'll get that given number of frames, instead of the default configured
amount. This is particularly useful to plug this stream into an audio device callback that wants a
variable number of frames per call.
functionstream_noise (sample_rate: int = 44100, channels: int = 1, noise_type: miniaudio.NoiseType = <NoiseType.WHITE: 0>, amplitude: float = 1.0, seed: int = 0, duplicate_channels: bool = False, sample_format: miniaudio.SampleFormat = <SampleFormat.FLOAT32: 5>, frames_to_read: int = 4096) -> 'PlaybackCallbackGeneratorType'
Convenience generator to stream (endless) noise as PCM audio.
Convenience generator function to stream raw pcm audio data from memory. Usually you don't need to
use this as the library provides many other streaming options that work on much smaller, encoded,
audio data. However, in the odd case that you only have already decoded raw pcm data you can use
this generator as a stream source. The data can be provided in array type or bytes,
memoryview or even a numpy array. Be sure to also specify the correct number of channels that
the audio data has, and the sample with in bytes.
Convenience generator function to add callback and processing functionality to another stream. You
can specify : > A callback function that gets called during play and takes an int for the number of
frames played. > A function that can be used to process raw data frames before they are yielded
back (takes an array.array or bytes, returns an array.array or bytes) *Note: if the processing
method is slow it will result in audio glitchiness > A callback function that gets called when the
stream ends playing.
Streams the ogg vorbis audio file as interleaved 16 bit signed integer sample arrays segments.
This uses a variable unconfigurable chunk size and cannot be used as a generic miniaudio decoder
input stream. Consider using stream_file() instead.
Reads and decodes the whole wav audio data. Resulting sample format is 32 bits signed integer.
functionwav_stream_file (filename: str, frames_to_read: int = 1024, seek_frame: int = 0) -> Generator[array.array, NoneType, NoneType]
Streams the WAV audio file as interleaved 16 bit signed integer sample arrays segments. This uses
a fixed chunk size and cannot be used as a generic miniaudio decoder input stream. Consider using
stream_file() instead.
Start the audio device: capture (recording) begins. The recorded audio data is sent to the given
callback generator as an array.array whose type matches the chosen sample format (e.g. array('h')
for SIGNED16, array('f') for FLOAT32). For SIGNED24, the data is sent as raw bytes. (the generator
should already be started before)
methodstop (self)
Halt playback or capture.
classDecodeError
DecodeError (self, /, *args, **kwargs)
When something went wrong during decoding an audio file.
Contains various properties and also the PCM frames of a fully decoded audio file. Inherits all
SoundFileInfo attributes (name, nchannels, sample_rate, sample_format, sample_width, num_frames,
duration, etc.) and adds .samples (array.array) which holds the raw PCM data. The array type matches
the sample format, e.g. array('h') for SIGNED16, array('f') for FLOAT32, array('B') for UNSIGNED8,
array('i') for SIGNED32.
Start the audio device: playback and capture begin. The audio data for playback is provided by
the given callback generator, which is sent the recorded audio data as an array.array whose type
matches the chosen capture format (e.g. array('h') for SIGNED16, array('f') for FLOAT32). (it should
already be started before passing it in)
A simple client for IceCast audio streams as miniaudio streamable source. If the stream has Icy
MetaData, the stream_title attribute will be updated with the actual title taken from the metadata.
You can also provide a callback to be called when a new stream title is available. The downloading
of the data from the internet is done in a background thread and it tries to keep a (small) buffer
filled with available data to read. You can optionally provide a custom ssl.SSLContext in the
ssl_context parameter, if you need to change the way SSL connections are configured (certificates,
checks, etc).
methodclose (self)
Stop the stream, aborting the background downloading.
Override this if the stream supports seeking. Note: seek support is sometimes not needed if you
give the file type to a decoder upfront. You can ignore this method then.
Start the audio device: playback begins. The audio data is provided by the given callback
generator. The generator gets sent the required number of frames and should yield the sample data as
raw bytes, a memoryview, an array.array, or as a numpy array with shape (numframes, numchannels).
The generator should already be started before passing it in.
Override this if the stream supports seeking. Note: seek support is sometimes not needed if you
give the file type to a decoder upfront. You can ignore this method then.