sound_rs v0.4.1

05 · Guides

Streaming and memory

play_file decodes incrementally. A decoder thread fills a one-second ring buffer, and the audio callback drains it. The ring size is independent of file length; container, decoder, resampler and process memory are additional.

How it works

When the sample rate changes, the resampler removes its filter delay and drains the filter tail at EOF. The output contains exactly ceil(input_frames * output_rate / input_rate) frames, including tracks shorter than a processing block. Seeking resets the filter and frame counters. This does not make independently resampled feed() blocks continuous; use the device rate for those blocks.

  1. The decoder thread reads a packet, decodes it to float32, converts the channel count and resamples to the device rate.
  2. The result goes into a ring buffer sized for one second of device audio.
  3. The audio callback pops samples from that buffer. When it is empty, the callback writes silence and keeps the stream alive.
  4. Seeking replaces the ring buffer and repositions the decoder; the old audio that was still queued is discarded and does not count towards the new position.

Playback can start before the full file is decoded. Startup still depends on device setup, container probing and any resampler buffering.

Numbers

Historical 0.3.0 measurements: ten-minute stereo FLAC, 44.1 kHz, measured with bench/run.py on an Apple M5 Pro. These are not current hardware guarantees:

sound_rssoundfile + sounddevice
Time to first sound11.3 ms302 ms
Peak RSS43 MB256 MB

The competitor number is not a flaw in those libraries: their API takes an array, so the file has to be decoded before playback can start. Streaming is a different design.

play_file or load?

You wantUseMemory
Play a filePlayer.play_file~1 s ring plus decoder/filter overhead
Analyse the samplesloadwhole file as float32
Play an array you already haveplay_arraycopied audio plus conversion temporaries
Play a file, need the samples tooload, then play_arraywhole file

Ten minutes of 44.1 kHz stereo float32 is about 212 MB of sample payload. Decoding and resampling can need additional temporary buffers.

import sound_rs

# streaming: bounded playback ring, incremental decode
with sound_rs.Player() as player:
    player.play_file("lecture-2h.m4a")
    player.wait()

# analysis: everything in RAM, decoded in parallel with other files
clips = sound_rs.load_many(["a.flac", "b.flac"])

Caveats