Pyminiaudio
python interface to the miniaudio audio playback, recording, decoding and conversion library
Install / Use
/learn @irmen/PyminiaudioREADME
Python miniaudio
Multiplatform audio playback, recording, decoding and sample format conversion for Linux (including Raspberri Pi), Windows, Mac and others.
Installation for most users: via Pypi, Raspberri 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
arraywith appropriately sized elements depending on the sample width (rather than a raw block of bytes) - TODO: filters, waveform generators?
Requires Python 3.10 or newer. Also works on pypy3 (because it uses cffi).
The miniaudio C library version is 0.11.25.
Software license for these Python bindings, miniaudio and the decoders: MIT
Synthesizer, modplayer?
If you like this library you may also be interested in my software FM synthesizer or my mod player which uses libxmp.
Examples
Basic audio file playback with info
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.
enum class Backend
names: WASAPI DSOUND WINMM COREAUDIO SNDIO AUDIO4 OSS PULSEAUDIO ALSA JACK AAUDIO OPENSL WEBAUDIO CUSTOM NULL
Operating system audio backend to use (only a subset will be available)
enum class ChannelMixMode
names: RECTANGULAR SIMPLE CUSTOMWEIGHTS
How to mix channels when converting
enum class DeviceType
names: PLAYBACK CAPTURE DUPLEX
Type of audio device
enum class DitherMode
names: NONE RECTANGLE TRIANGLE
How to dither when converting
enum class FileFormat
names: UNKNOWN WAV FLAC MP3 VORBIS
Audio file format
enum class SampleFormat
names: UNKNOWN UNSIGNED8 SIGNED16 SIGNED24 SIGNED32 FLOAT32
Sample format in memory
enum class SeekOrigin
names: START CURRENT END
How to seek() in a source
enum class ThreadPriority
names: IDLE LOWEST LOW NORMAL HIGH HIGHEST REALTIME
The priority of the worker thread (default=HIGHEST)
function convert_frames (from_fmt: miniaudio.SampleFormat, from_numchannels: int, from_samplerate: int, sourcedata: bytes, to_fmt: miniaudio.SampleFormat, to_numchannels: int, to_samplerate: int) -> bytearray
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.
function convert_sample_format (from_fmt: miniaudio.SampleFormat, sourcedata: bytes, to_fmt: miniaudio.SampleFormat, dither: miniaudio.DitherMode = <DitherMode.NONE: 0>) -> bytearray
Convert a raw buffer of pcm samples to another sample format. The result is returned as another raw pcm sample buffer
function decode (data: bytes, output_format: miniaudio.SampleFormat = <SampleFormat.SIGNED16: 2>, nchannels: int = 2, sample_rate: int = 44100, dither: miniaudio.DitherMode = <DitherMode.NONE: 0>) -> miniaudio.DecodedSoundFile
Convenience function to decode any supported audio file in memory to raw PCM samples in your chosen format.
function decode_file (filename: str, output_format: miniaudio.SampleFormat = <SampleFormat.SIGNED16: 2>, nchannels: int = 2, sample_rate: int = 44100, dither: miniaudio.DitherMode = <DitherMode.NONE: 0>) -> miniaudio.DecodedSoundFile
Convenience function to decode any supported audio file to raw PCM samples in your chosen format.
function flac_get_file_info (filename: str) -> miniaudio.SoundFileInfo
Fetch some information about the audio file (flac format).
function flac_get_info (data: bytes) -> miniaudio.SoundFileInfo
Fetch some information about the audio data (flac format).
function flac_read_f32 (data: bytes) -> miniaudio.DecodedSoundFile
Reads and decodes the whole flac audio file. Resulting sample format is 32 bits float.
function flac_read_file_f32 (filename: str) -> miniaudio.DecodedSoundFile
Reads and decodes the whole flac audio file. Resulting sample format is 32 bits float.
function flac_read_file_s16 (filename: str) -> miniaudio.DecodedSoundFile
Reads and decodes the whole flac audio file. Resulting sample format is 16 bits signed integer.
function flac_read_file_s32 (filename: str) -> miniaudio.DecodedSoundFile
Reads and decodes the whole flac audio file. Resulting sample format is 32 bits signed integer.
function flac_read_s16 (data: bytes) -> miniaudio.DecodedSoundFile
Reads and decodes the whole flac audio data. Resulting sample format is 16 bits signed integer.
function flac_read_s32 (data: bytes) -> miniaudio.DecodedSoundFile
Reads and decodes the whole flac audio data. Resulting sample format is 32 bits signed integer.
function flac_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.
function get_enabled_backends () -> Set[miniaudio.Backend]
Returns the set of available backends by the compilation environment for the underlying miniaudio C library
function get_file_info (filename: str) -> miniaudio.SoundFileInfo
Fetch some information about the audio file.
function is_backend_enabled (backend: miniaudio.Backend) -> bool
Determines whether or not the given backend is available by the compilation environment for the underlying miniaudio C library
function is_loopback_supported (backend: miniaudio.Backend) -> bool
Determines whether or not loopback mode is support by a backend.
function lib_version () -> str
Returns the version string of the underlying miniaudio C library
function mp3_get_file_info (filename: str) -> miniaudio.SoundFileInfo
Fetch some information about the audio file (mp3 format).
function mp3_get_info (data: bytes) -> miniaudio.SoundFileInfo
Fetch some information about the audio data (mp3 format).
function mp3_read_f32 (data: bytes) -> miniaudio.DecodedSoundFile
Reads and decodes the whole mp3 audio data. Resulting sample format is 32 bits float.
function mp3_read_file_f32 (filename: str) -> miniaudio.DecodedSoundFile
Reads and decodes the who
Related Skills
node-connect
343.3kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
92.1kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
343.3kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
343.3kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
