audiofilewriter – Support for streaming audio to a WAV file
Available on these boards
- class audiofilewriter.AudioFileWriter(file: BinaryIO, *, buffer_size: int = 32768)
Streams an audio source to a
.wavfile in the background.AudioFileWriteris the inverse ofaudiocore.WaveFile: rather than being an audio source played by anaudioio.AudioOut, it is a sink that drives an audio source (a microphone,synthio, or anaudiofilters/audiodelays/audiofreeverb/audiospeedeffect chain) and writes the resulting PCM to a file as a WAV.Recording runs on a background pump paced to the source’s real-time rate, so it does not block and does not require a Python read loop.
Create an
AudioFileWriterthat writes tofile.- Parameters:
file (BinaryIO) – An already-open writable binary stream (a file opened in
"wb"mode, or anio.BytesIO). The stream must support seeking so the WAV header sizes can be patched when recording stops.AudioFileWriterdoes not close it; the caller owns it.buffer_size (int) – Size in bytes of the internal RAM ring that decouples file-write latency from the source. Larger values tolerate longer write stalls (e.g. a slow SD card) at the cost of RAM. Minimum valid value, and default, is
512. Must be at least the size of the source buffer.
The audio format (sample rate, channel count, bit depth) is taken from the source at
play()time, so there are no format arguments here.Recording synthio to SD:
import time import synthio from audiofilewriter import AudioFileWriter import storage SAMPLE_RATE = 16000 OUTPUT_PATH = "/sd/demo_file.wav" C_major_scale = [60, 62, 64, 65, 67, 69, 71, 72, 71, 69, 67, 65, 64, 62, 60] synth = synthio.Synthesizer(sample_rate=SAMPLE_RATE) with open(OUTPUT_PATH, "wb") as f: writer = AudioFileWriter(f) writer.play(synth) for note in C_major_scale: synth.press(note) time.sleep(0.1) synth.release(note) time.sleep(0.10) writer.stop() print("Done ->", OUTPUT_PATH)
- __enter__() AudioFileWriter
No-op used by Context Managers.
- __exit__() None
Automatically deinitializes when exiting a context. See Lifetime and ContextManagers for more info.
- play(sample: circuitpython_typing.AudioSample) None
Begin recording
sampleto the file. Does not block.Writes a WAV header (in the format of
sample) and starts the background pump.samplemust be an 8-bit or 16-bit mono or stereo audio source. Useplayingto tell when a finite source has finished, or callstop()to end recording of a continuous source (e.g. a mic).