audiofilewriter – Support for streaming audio to a WAV file
Available on these boards
- class audiofilewriter.AudioFileWriter(file: BinaryIO | None, *, 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.Nonewrites nothing: the source is still played at its real-time rate, and its audio is dropped. That keeps audio flowing through anaudiotap.Tapon a board with no audio output.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 is
512. Must be at least the size of the source buffer. Not used whenfileisNone.
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)
Measuring levels on a USB microphone on the Metro ESP32-P4. The
adafruit_usb_host_descriptorslibrary finds the microphone and its format, andusb.corestarts its stream; seeusb_host_audio.USBIn:import time import adafruit_usb_host_descriptors import audiotap import board import digitalio import usb_host import usb_host_audio from audiofilewriter import AudioFileWriter # The Metro's USB host port isn't started by the board: power it and start it. usb_power = digitalio.DigitalInOut(board.USB_HOST_POWER) usb_power.switch_to_output(value=True) usb_port = usb_host.Port(board.USB_HOST_DP, board.USB_HOST_DM) # Give a microphone that is already plugged in time to enumerate. device = None deadline = time.monotonic() + 3 while device is None and time.monotonic() < deadline: device = adafruit_usb_host_descriptors.find_microphone() time.sleep(0.1) if device is None: raise RuntimeError("Plug a USB microphone or webcam into the USB host port") formats = adafruit_usb_host_descriptors.find_microphone_formats(device) mic_format = adafruit_usb_host_descriptors.choose_microphone_format(formats, sample_rate=48000) sample_rate = mic_format.nearest_rate(48000) device.set_configuration() # SET_INTERFACE to the format's alternate setting starts the stream, then # SET_CUR of the endpoint's sampling frequency picks the rate. device.ctrl_transfer(0x01, 11, mic_format.alternate, mic_format.interface, None) if mic_format.rate_control: device.ctrl_transfer( 0x22, 0x01, 0x0100, mic_format.endpoint, sample_rate.to_bytes(3, "little") ) mic = usb_host_audio.USBIn( device, mic_format.endpoint, sample_rate=sample_rate, channel_count=mic_format.channel_count, bit_depth=8 * mic_format.bytes_per_sample, samples_signed=mic_format.samples_signed, max_packet_size=mic_format.max_packet_size, ) # The tap only measures the levels, so it keeps no audio. tap = audiotap.Tap(capacity=0) # No file: fetch buffers through the tap at the microphone's rate and drop them. sink = AudioFileWriter(None) sink.play(tap.play(mic)) while True: print(f"peak {tap.peak:.3f} rms {tap.rms:.3f}") time.sleep(0.5)
- __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).