usb_host_audio – Audio from USB devices connected to a USB host port.
The usb_host_audio module contains the USBIn class, which streams the
audio of a USB microphone into the audio pipeline or records it.
This module only moves the audio. Finding the microphone, picking one of its
formats and starting its stream is done with usb.core, for example by the
adafruit_usb_host_microphone library.
All classes change hardware state and should be deinitialized when they
are no longer needed. To do so, either call deinit() or use a
context manager.
Available on these boards
- class usb_host_audio.USBIn(device: usb.core.Device, endpoint: int, *, sample_rate: int, channel_count: int = 1, bit_depth: int = 16, samples_signed: bool = True, max_packet_size: int = 0, buffer_frames: int = 256, iso_buffer_size: int = 16384)
Stream or record the audio of a USB microphone on a USB host port.
Receive the PCM audio that a USB Audio Class microphone sends on an isochronous IN endpoint. The object can be played like any other audio sample, which makes the microphone the source of an audio effects chain, and it can
recordto a buffer.The constructor does no control transfers. Before calling it, select the alternate setting of the streaming interface that has
endpointand set the sample rate; the arguments describe the format chosen that way. Do not create aUSBInfor an interface that is in alternate setting 0.deinitselects alternate setting 0 again, so the microphone stops also when awithblock is left by an exception, or when the program ends.On RP2 boards, whose host port is PIO-USB, the host controller buffers the stream between reads, in a buffer of
iso_buffer_sizebytes thatUSBInallocates anddeinitfrees. On boards whose host port is the chip’s own USB controller, such as the Metro ESP32-P4, there is no such buffer andiso_buffer_sizeis not used: each packet is received as it arrives, and packets that arrive while background tasks can’t run, such as during a long garbage collection, are lost and setoverflow.Only one isochronous IN endpoint is received at a time, so only one
USBIncan stream, and a USB camera cannot stream video meanwhile. Creating a second one raisesRuntimeErrorwhile the first isstreaming, and deinitializes the first when its stream has ended.The microphone’s clock is independent of the clock of the audio output. While playing, the drift between them is taken up by stretching a buffer by one frame now and then, which cannot be heard. Only when playback stalls is audio dropped, which sets
overflow, or a moment of silence played. About3 * buffer_framesframes of latency are added.- Parameters:
device (Device) – The microphone. Its configuration must be set.
endpoint (int) – The address of the isochronous IN endpoint
sample_rate (int) – The sample rate that the microphone was set to, in Hz
channel_count (int) – The number of channels in the stream
bit_depth (int) – The bits per sample in the stream: 8, 16, 24 or 32. 24 and 32 bit samples are narrowed to 16 bit; see
bits_per_sample. For samples narrower than their bytes, such as 24 bits in 4 bytes, give the size of the bytes.samples_signed (bool) – Samples are signed (True) or unsigned (False). USB audio is signed, except for 8 bit PCM.
max_packet_size (int) – The endpoint’s
wMaxPacketSizebuffer_frames (int) – The number of frames handed to the audio pipeline at a time
iso_buffer_size (int) – The size in bytes of the host controller’s buffer for the stream, from 2048 to 65536, rounded up to a power of two. It holds the packets that arrive while background tasks don’t run, each with 2 bytes of overhead: 16384 is about half a second of 16 kHz mono audio or 80 ms of 48 kHz stereo. Only used on RP2 boards; ignored on the Metro ESP32-P4 and other boards whose host port is the chip’s own USB controller.
Example, recording a second from the microphone of a Logitech C270 webcam. It streams 16 bit mono on interface 3, alternate setting 1, endpoint 0x86. For another microphone, read these from its configuration descriptor:
import array import usb.core import usb_host_audio device = usb.core.find(idVendor=0x046D, idProduct=0x0825) device.set_configuration() # SET_INTERFACE to alternate setting 1 starts the stream, then # SET_CUR of the endpoint's sampling frequency picks 16 kHz. device.ctrl_transfer(0x01, 11, 1, 3, None) device.ctrl_transfer(0x22, 0x01, 0x0100, 0x86, (16000).to_bytes(3, "little")) samples = array.array("h", [0] * 16000) # Leaving the with block stops the stream. with usb_host_audio.USBIn(device, 0x86, sample_rate=16000, max_packet_size=68) as mic: count = mic.record(samples, len(samples)) print("recorded", count, "samples, peak", max(abs(s) for s in samples))
- deinit() None
Stops the stream and releases the buffers. While the stream is still
streaming, this selects alternate setting 0 of the endpoint’s interface first, which stops the microphone sending.
- __exit__() None
Automatically deinitializes the hardware when exiting a context. See Lifetime and ContextManagers for more info.
- record(destination: circuitpython_typing.WriteableBuffer, destination_length: int) int
Records destination_length samples to destination. This is blocking. A stereo frame is two samples, left then right.
destinationis anarray.arrayof typecode'h'forbits_per_sample16 ('H'when unsigned), and of typecode'b'('B'when unsigned) or abytearrayfor 8.Audio is received between calls too, so that consecutive recordings join up. When more arrived than is buffered, the recording starts with the audio that arrives after the call.
- Returns:
The number of samples recorded. If this is less than
destination_length, the microphone stopped sending audio.
- sample_rate: int
The sample rate given to the constructor, in Hz. This is the rate reported to the audio pipeline. The microphone’s own clock decides the true rate, which is usually a fraction of a percent off.
- bits_per_sample: int
The number of bits per sample as it is streamed through the audio pipeline and recorded: 8 or 16. (read-only)
- streaming: bool
True while the stream is received. It turns False for good when the microphone stops sending: an alternate setting of the device was selected, its configuration was set again, it was unplugged, or another isochronous stream was started. The object then plays silence and records only what it received before; make a new one after starting the stream again. (read-only)
Receiving is not retried, because some devices stop answering control requests when an endpoint of an idle interface is polled.
- overflow: bool
True if audio was dropped since the last time this was checked: it was not played or recorded fast enough, or the host controller lost packets. (read-only)
Reading this clears the flag. Audio that arrives while nothing plays or records also overflows, except that starting playback discards it without setting the flag.