librosa.StreamBridge#
- class librosa.StreamBridge(*, orig_sr, channels=1, channels_first=False, dtype=<class 'numpy.float32'>, maxsize=0, overflow_policy='warn', timeout=None)[source]#
Universal I/O bridge connecting audio callbacks into
librosa.stream.StreamBridgeacts as an audio callback (compatible with PortAudio,sounddevice, andPyAudio) that enqueues incoming raw audio chunks, and simultaneously acts as an iterator of Librosa-canonical NumPy arrays.- Parameters:
- orig_srfloat > 0
Sampling rate of the incoming audio stream (required keyword-only argument).
- channelsint > 0, default=1
Number of audio channels in the incoming stream.
- channels_firstbool, default=False
If True, incoming multi-channel buffers are shaped
(channels, samples). If False, incoming multi-channel buffers are shaped(samples, channels)(standard forsounddeviceand PortAudio) and will be transposed to canonical shape(channels, samples).- dtypeDTypeLike, default=np.float32
Data type of incoming audio chunks or byte buffers. If integer PCM, samples are normalized to floating-point
[-1.0, 1.0]according to their integer bit depth.- maxsizeint >= 0, default=0
Maximum capacity of the internal chunk buffer. If 0, capacity is unbounded. For live real-time hardware streams where downstream processing might intermittently stall, setting a bounded capacity (e.g.
maxsize=100) combined withoverflow_policy="drop_oldest"prevents uncontrolled memory growth and latency accumulation.- overflow_policy{‘warn’, ‘drop_oldest’, ‘drop_newest’, ‘error’}, default=’warn’
- Action taken when maxsize is reached:
"warn": Discard the oldest queued chunk and emit a warning when chunks are retrieved."drop_oldest": Discard the oldest queued chunk (fixed-latency ring buffer)."drop_newest": Discard the incoming chunk."error": Raise BufferError.
- timeoutfloat | None, default=None
Maximum time in seconds to wait for a chunk during iteration before raising
queue.Empty. IfNone, blocks indefinitely.
Examples
Bridge real-time input from
sounddeviceand stream analysis blocks. Note that streaming analysis requires left-aligned frames, so we passcenter=Falseto avoid boundary padding artifacts between blocks. For a complete walkthrough, see Live stream processing.>>> import sounddevice as sd >>> with librosa.StreamBridge( ... orig_sr=48000, channels=1 ... ) as bridge: ... with sd.InputStream(samplerate=48000, channels=1, callback=bridge): ... for i, block in enumerate( ... bridge.stream( ... block_length=256, frame_length=2048, hop_length=512, sr=None ... ) ... ): ... centroid = librosa.feature.spectral_centroid( ... y=block, sr=48000, n_fft=2048, hop_length=512, center=False ... ) ... print(f"Block {i}: mean centroid = {centroid.mean():.1f} Hz") ... if i >= 10: ... break
- __init__(*, orig_sr, channels=1, channels_first=False, dtype=<class 'numpy.float32'>, maxsize=0, overflow_policy='warn', timeout=None)[source]#
Methods
close()Close the bridge and signal termination to waiting consumers.
push(data)Push a raw audio chunk into the bridge.
stream(*, block_length, frame_length, hop_length)Stream audio from this bridge in fixed-length analysis buffers.
- push(data)[source]#
Push a raw audio chunk into the bridge.
- Parameters:
- datanp.ndarray, bytes, or memoryview
Incoming audio buffer. Integer arrays or byte buffers are converted to float32 according to dtype. Single-channel audio is normalized to 1D shape
(samples,), and multi-channel audio is normalized to shape(channels, samples).
- stream(*, block_length, frame_length, hop_length, sr=22050, mono=True, offset=0.0, duration=None, warm_up=False, fill_value=None, res_type='soxr_hq', dtype=<class 'numpy.float32'>)[source]#
Stream audio from this bridge in fixed-length analysis buffers.
This method is equivalent to calling
librosa.stream(self, ...).- Parameters:
- block_lengthint > 0
The number of frames to include in each block.
- frame_lengthint > 0
The number of samples per frame.
- hop_lengthint > 0
The number of samples to advance between frames.
- srfloat > 0, default=22050
Target sampling rate. If None, uses self.orig_sr without resampling.
- monobool, default=True
Convert multi-channel signals to mono during streaming.
- offsetfloat >= 0, default=0.0
Start reading after this time (in seconds).
- durationfloat > 0, optional
Only yield up to this much audio (in seconds).
- warm_upbool, default=False
If True, pre-fill the buffer with silence (zeros) so that the first incoming chunk of size
block_length * hop_lengthimmediately yields a full analysis block without startup delay.- fill_valuefloat, optional
Value used to pad short blocks at the end of the stream.
- res_typestr, default=’soxr_hq’
Resample type for
soxr.- dtypenumeric type, default=np.float32
Data type of the yielded blocks.
- Yields:
- blocknp.ndarray
An audio buffer of (at most)
(block_length-1) * hop_length + frame_lengthsamples.
See also
Attributes
Sampling rate of the incoming audio stream.
- sr#
Sampling rate of the incoming audio stream.
Alias for orig_sr.
- Returns:
- srfloat
Sampling rate of the incoming audio stream.