Miniaudio Python Bindings

1.61 · active · verified Thu Apr 16

miniaudio provides Python bindings for the `miniaudio` C library, offering cross-platform audio playback and decoding capabilities. It includes built-in decoders for common formats like MP3, FLAC, OGG Vorbis, and WAV. The library is actively maintained, with frequent releases (roughly monthly to bi-monthly) often focusing on updates to the underlying C library and Python version compatibility. The current version is 1.61.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to generate a sine wave using NumPy and play it directly using `miniaudio.stream_raw_pcm_memory`. It sets up a `PlaybackDevice`, creates a stream from the raw audio data, plays it, and then waits for the playback duration. This avoids reliance on external audio files.

import miniaudio
import numpy as np
import time

def get_sine_wave(frequency, duration, sample_rate=44100, amplitude=0.5):
    """Generates a raw 16-bit PCM sine wave as bytes."""
    t = np.linspace(0, duration, int(sample_rate * duration), False)
    amplitude_scale = np.iinfo(np.int16).max * amplitude
    data = (amplitude_scale * np.sin(2 * np.pi * frequency * t)).astype(np.int16)
    return data.tobytes()

# Play a 440 Hz sine wave for 3 seconds
with miniaudio.PlaybackDevice() as device:
    print("Playing a 440 Hz sine wave for 3 seconds...")
    sine_data = get_sine_wave(440, 3)
    # Create a stream from raw PCM bytes
    stream = miniaudio.stream_raw_pcm_memory(
        sine_data,
        sample_rate=44100,
        nchannels=1,
        output_format=miniaudio.SampleFormat.SIGNED16
    )
    device.play(stream)
    time.sleep(3) # Wait for playback to finish
    print("Finished playing.")

view raw JSON →