Python Streaming API
Block-by-block processors of the libsonare Python package: the realtime voice changer, StreamingRetune and the streaming equalizer. Each keeps its state across blocks, owns native memory, and releases it through close() or a with block (Releasing Native Handles). The incremental StreamAnalyzer is covered in Streaming Analysis API, and the streaming mastering chain on Python Mastering API, and the movie-audio playback renderer on Python Playback API.
Realtime voice changer
RealtimeVoiceChanger wraps the same preset-based live voice chain exposed by WASM and Node native. It keeps high-pass, gate, retune, formant, EQ, compressor, de-esser, reverb, and limiter state across blocks. Use it instead of voice_change(...) when processing microphone or stream blocks.
import json
import libsonare as sonare
print(sonare.realtime_voice_changer_preset_names())
print(sonare.voice_changer_abi_version()) # native POD-config ABI version
print(sonare.voice_character_preset_id(1)) # "brightIdol"
preset_json = sonare.realtime_voice_changer_preset_json("brightIdol")
print(sonare.validate_realtime_voice_changer_preset_json(preset_json)["ok"])
preset_config = sonare.realtime_voice_changer_preset_config("brightIdol") # canonical RealtimeVoiceChangerConfig
with sonare.RealtimeVoiceChanger(48000, num_channels=1, config="brightIdol", max_block_size=128) as changer:
out = changer.process_mono(input_block)
changer.set_config(json.loads(preset_json))
print(changer.latency_samples, changer.config_json(), out.shape)
# Convenience one-shot render through the same realtime chain.
processed = sonare.realtime_voice_changer_render(vocal, 48000, config="softWhisper")Preset IDs currently include neutralMonitor, brightIdol, softWhisper, deepNarrator, robotMascot, darkVillain, hardTune, robotMonotone, choirHarmony, vocoderStrings, megaphone, and radioVoice.
Built-in IDs are the strict canonical strings shown above. A custom mapping must pass the preset JSON validator and contain either a dsp object or a macros object, not both; malformed preset shapes are rejected.
Use realtime_voice_changer_preset_config(preset) when you want the resolved POD config rather than the JSON form. It returns the canonical, normalized RealtimeVoiceChangerConfig for a built-in preset named by its VoicePresetId; an index is a TypeError, so turn one into an ID with voice_character_preset_id(index) first.
formant_mode ("relative" by default, or "absolute") is fixed when the changer is created (preset key dsp.formant.mode); With voice_engine="grain", absolute mode adds one analysis frame of latency and refuses an unreachable computed warp. The default PSOLA engine adds no mode-dependent latency. A configuration value that is non-finite or out of range, in the constructor or in a later config update, is refused by name and the changer keeps its previous configuration. For stereo, construct the changer with num_channels=2 and call process_planar([left, right]) or process_interleaved(samples, num_channels). StreamingRetune(pitch_semitones=, mix=, grain_size_samples=) runs the retune stage on its own, block by block (call prepare(sample_rate, max_block_size) first).
Preset functions
realtime_voice_changer_preset_names() lists the built-in presets and realtime_voice_changer_preset_json(name) returns one preset's JSON text (SonareError for an unknown name). validate_realtime_voice_changer_preset_json(json_text) validates a preset JSON text and returns the verdict as a dict rather than raising.
# Return the names of the built-in realtime voice-changer presets.
def realtime_voice_changer_preset_names() -> list[str]: ...
# Return the JSON text of the named preset.
def realtime_voice_changer_preset_json(name: str) -> str: ...
# Validate a preset JSON text; return the verdict as a dict rather than raising.
def validate_realtime_voice_changer_preset_json(document: str) -> dict[str, object]: ...RealtimeVoiceChanger
# Streaming realtime voice changer backed by the libsonare C API.
class RealtimeVoiceChanger:
# Create a voice changer for ``num_channels`` (1 or 2) at ``sample_rate``.
def __init__(
self,
sample_rate: int,
*,
num_channels: int,
config: VoicePresetId | RealtimeVoiceChangerPreset | RealtimeVoiceChangerConfig = 'neutralMonitor',
max_block_size: int | None = None,
) -> None: ...
# Release the native handle.
def close(self) -> None: ...
# Return self so the object works as a context manager.
def __enter__(self) -> RealtimeVoiceChanger: ...
# Close on leaving the ``with`` block; never suppresses an exception.
def __exit__(self, exc_type: object, exc: object, tb: object) -> None: ...
# Clear the processing state.
def reset(self) -> None: ...
# Apply a preset id, a configuration document mapping or a config record.
def set_config(
self,
config: VoicePresetId | RealtimeVoiceChangerPreset | RealtimeVoiceChangerConfig,
) -> None: ...
# The largest block one native call accepts; ``process_*`` chunk longer input to it.
@property
def max_block_size(self) -> int: ...
# Processing latency in samples.
@property
def latency_samples(self) -> int: ...
# Return the blocks in which the chain discarded its own state.
@property
def non_finite_discard_count(self) -> int: ...
# Return the live (normalized) configuration as a JSON document.
def config_json(self) -> str: ...
# The live (normalized) configuration as a :class:`RealtimeVoiceChangerConfig` record.
@property
def config(self) -> RealtimeVoiceChangerConfig: ...
# Process a mono buffer block-by-block and return the result as ndarray.
def process_mono(
self,
samples: Sequence[float] | list[float] | np.ndarray,
carrier: Sequence[float] | list[float] | np.ndarray | None = None,
) -> np.ndarray: ...
# Process an interleaved (LRLR...) buffer block-by-block.
def process_interleaved(
self,
samples: Sequence[float] | list[float] | np.ndarray,
num_channels: int | None = None,
carrier: Sequence[float] | list[float] | np.ndarray | None = None,
) -> np.ndarray: ...
# Process planar audio (one buffer per channel, 1 or 2, equal lengths) block-by-block.
def process_planar(
self,
channels: PlanarChannels,
carrier: Sequence[float] | list[float] | np.ndarray | None = None,
) -> list[np.ndarray]: ...
# Hold MIDI ``note`` from the start of the next processed block.
def note_on(self, note: int, velocity: float = 1.0) -> None: ...
# Release MIDI ``note``; releasing a note that is not held does nothing.
def note_off(self, note: int) -> None: ...
# Release every held note; succeeds even when the event queue is full.
def all_notes_off(self) -> None: ...Streaming Equalizer API
StreamingEqualizer wraps the native block-by-block EQ engine. Use it for live preview, processor UIs, or matching a source tone to a reference without assembling a mastering chain.
with sonare.StreamingEqualizer(sample_rate=48000, max_block_size=512) as eq:
eq.set_band(0, {"type": "peak", "frequencyHz": 2500, "gainDb": 2.5, "q": 1.0})
eq.set_phase_mode("natural")
eq.set_auto_gain(True)
# buffers may differ in length; the reference may be at its own rate
eq.match(source_samples, reference_samples, max_bands=8, reference_sample_rate=44100)
out = eq.process_mono(input_block)
snapshot = eq.spectrum()Bands are Python dictionaries (parse JSON text with json.loads first). set_phase_mode(...) accepts the names zero, natural and linear. The object also exposes output gain/pan, sidechain input for dynamic bands, process_stereo(...), spectrum(), latency_samples, and last_auto_gain_db.
# Block-by-block unified EQ wrapper around the native ``SonareEq`` handle.
class StreamingEqualizer:
sample_rate: int
# Create an equalizer; an omitted ``max_block_size`` takes the library default.
def __init__(self, *, sample_rate: int, max_block_size: int | None = None) -> None: ...
# Set one EQ band from an :data:`EqBandInput` mapping.
def set_band(self, index: int, band: EqBandInput) -> None: ...
# Clear all EQ bands.
def clear(self) -> None: ...
# Set the global phase mode: ``"zero"``, ``"natural"`` or ``"linear"``.
def set_phase_mode(self, mode: EqPhaseMode) -> None: ...
# Enable or disable auto-gain compensation.
def set_auto_gain(self, enabled: bool) -> None: ...
# Set all-band EQ gain scale as a 0.0..2.0 multiplier.
def set_gain_scale(self, scale: float) -> None: ...
# Set post-EQ output gain in dB.
def set_output_gain_db(self, gain_db: float) -> None: ...
# Set post-EQ stereo balance in -1.0..1.0; mono input ignores pan.
def set_output_pan(self, pan: float) -> None: ...
# Set a mono external key for dynamic bands with ``externalSidechain`` enabled.
def set_sidechain_mono(self, samples: Sequence[float] | np.ndarray) -> None: ...
# Set a stereo external key for dynamic bands with ``externalSidechain`` enabled.
def set_sidechain_stereo(
self,
left: Sequence[float] | np.ndarray,
right: Sequence[float] | np.ndarray,
) -> None: ...
# Clear any pending external key buffer.
def clear_sidechain(self) -> None: ...
# Configure live EQ bands by matching ``source`` to ``reference``.
def match(
self,
source: Sequence[float] | np.ndarray,
reference: Sequence[float] | np.ndarray,
*,
max_bands: int = 8,
sample_rate: int | None = None,
reference_sample_rate: int | None = None,
) -> None: ...
# Process one mono block, returning processed samples.
def process_mono(self, samples: Sequence[float] | np.ndarray) -> np.ndarray: ...
# Process one stereo block, returning the processed (left, right) channels.
def process_stereo(
self,
left: Sequence[float] | np.ndarray,
right: Sequence[float] | np.ndarray,
) -> StereoBlock: ...
# Return the latest pre/post sample stream and band-gain snapshot.
def spectrum(self) -> EqSpectrumSnapshot: ...
# Return the composite magnitude of the bands, in dB, at each frequency.
def magnitude_response(
self,
frequencies_hz: Sequence[float] | np.ndarray,
*,
placement: EqStereoPlacement = 'stereo',
) -> np.ndarray: ...
# The largest block one ``process_*`` call accepts.
@property
def max_block_size(self) -> int: ...
# Processing latency in samples.
@property
def latency_samples(self) -> int: ...
# Automatic output gain (dB) applied by the latest process call.
@property
def last_auto_gain_db(self) -> float: ...
# Blocks in which the equalizer discarded recursive state.
@property
def non_finite_discard_count(self) -> int: ...
# Release the underlying C handle.
def close(self) -> None: ...
# Return the object itself for ``with`` use.
def __enter__(self) -> StreamingEqualizer: ...
# Close the object on leaving the ``with`` block; never suppresses exceptions.
def __exit__(self, exc_type: object, exc: object, tb: object) -> None: ...Streaming retune
StreamingRetune is a block-by-block mono pitch shifter (grain overlap-add), the streaming counterpart of the offline pitch_shift. Its state persists across process_mono(...) calls, so consecutive blocks join without a seam, and prepare(...) must be called before processing. pitch_semitones must be finite and in [-24, 24] and mix finite and in [0, 1]; a value outside either raises SonareValueError.
# Block-by-block mono pitch shifter (grain overlap-add).
class StreamingRetune:
def __init__(
self,
*,
pitch_semitones: float = 0.0,
mix: float = 1.0,
grain_size_samples: int | None = None,
) -> None: ...
# Release the native handle.
def close(self) -> None: ...
# Return self so the object works as a context manager.
def __enter__(self) -> StreamingRetune: ...
# Close on leaving the ``with`` block; never suppresses an exception.
def __exit__(self, exc_type: object, exc: object, tb: object) -> None: ...
# Allocate for an integer rate [8000, 384000] Hz and block size [1, 1048576].
def prepare(self, sample_rate: int, max_block_size: int) -> None: ...
# Clear grain / overlap-add state without changing the config.
def reset(self) -> None: ...
# Update the live controls; omitted keywords keep their current value.
def set_config(
self,
*,
pitch_semitones: float | None = None,
mix: float | None = None,
grain_size_samples: int | None = None,
) -> None: ...
# The controls as configured; ``grain_size_samples`` is ``None`` when automatic.
def config(self) -> dict[str, float | int | None]: ...
# Resolved grain length in samples; 0 before :meth:`prepare`.
@property
def grain_size_samples(self) -> int: ...
# Fixed overlap-add latency in samples (one grain); 0 before prepare.
@property
def latency_samples(self) -> int: ...
# Process one mono block, returning the shifted samples (same length).
def process_mono(self, samples: Sequence[float] | list[float] | np.ndarray) -> np.ndarray: ...Streaming Analysis API
Use StreamAnalyzer when audio arrives in blocks: live capture, a callback loop, a long file you do not want to analyze all at once, or a visualization that needs frame-by-frame features. It keeps a small internal buffer, emits mel/chroma/onset/spectral frames, and periodically updates BPM, key, chord, bar, and pattern estimates.
import libsonare as sonare
with sonare.StreamAnalyzer(sample_rate=44100, n_mels=64, emit_every_n_frames=4) as stream:
for block in audio_blocks:
stream.process(block)
frames = stream.read_frames(stream.available_frames)
# frames.mel is linear mel power, shape (n_mels, n_frames); None when compute_mel is off
# frames.chroma has shape (n_chroma, n_frames); None when compute_chroma is off
estimate = stream.stats().estimate
if estimate.bpm is not None:
print(estimate.bpm, estimate.bpm_confidence)The analyzer is configured through keyword arguments (all but sample_rate optional): n_fft, hop_length, n_mels, fmin_hz, fmax_hz, reference_hz, compute_mel, compute_chroma, compute_onset, compute_spectral, emit_every_n_frames, max_pending_frames, max_progression_entries, key_update_interval_sec, bpm_update_interval_sec and window; an omitted option takes the library default.
For lower-bandwidth UI transfer, use a quantized read instead of read_frames(max_frames):
| Method | What changes |
|---|---|
read_quantized_frames_u8(max_frames, quantize_config?) | Feature arrays are quantized to unsigned 8-bit values (StreamFramesU8). |
read_quantized_frames_i16(max_frames, quantize_config?) | Feature arrays are quantized to signed 16-bit values (StreamFramesI16). |
quantize_config is an optional StreamQuantizeConfig (exported from libsonare) that widens the quantization ranges for streams much louder or quieter than the defaults; omit it to use the defaults. Its fields and defaults are mel_db_min=-80.0, mel_db_max=0.0, onset_max=50.0, rms_max=1.0, centroid_max=11025.0. The quantizers clamp normalized values to [0, 1], so a signal outside these ranges otherwise saturates silently to the endpoints. This mirrors StreamQuantizeConfig in the JS/WASM streaming documentation.
All three reads return timestamps_sec as floats. If you synchronize against an external audio clock, feed chunks with process(samples, start_sample) so returned timestamps follow that timeline.
process with a start_sample accepts only contiguous offsets. After a gap, seek, or switching from process(samples) without an offset, call reset(start_sample) before feeding the next block. max_progression_entries (default 4096) bounds each retained chord and bar progression; stats() exposes dropped_chord_progression_entries and dropped_bar_progression_entries when the oldest history is discarded, and non_finite_discard_blocks when NaN or Inf input was replaced.
StreamAnalyzer signatures
# Thin Python wrapper around the native streaming frame analyzer handle.
class StreamAnalyzer:
# Create an analyzer for input at ``sample_rate``.
def __init__(
self,
*,
sample_rate: int,
n_fft: int | None = None,
hop_length: int | None = None,
n_mels: int | None = None,
fmin_hz: float | None = None,
fmax_hz: float | None = None,
reference_hz: float | None = None,
compute_mel: bool | None = None,
compute_chroma: bool | None = None,
compute_onset: bool | None = None,
compute_spectral: bool | None = None,
emit_every_n_frames: int | None = None,
max_pending_frames: int | None = None,
max_progression_entries: int | None = None,
key_update_interval_sec: float | None = None,
bpm_update_interval_sec: float | None = None,
window: WindowType | None = None,
) -> None: ...
# Release the native handle.
def close(self) -> None: ...
# Return self so the object works as a context manager.
def __enter__(self) -> StreamAnalyzer: ...
# Close on leaving the ``with`` block; never suppresses an exception.
def __exit__(self, *_exc: object) -> None: ...
# Feed an audio chunk.
def process(
self,
samples: Sequence[float] | list[float],
start_sample: int | None = None,
) -> None: ...
# Drain any high-rate resampler tail, then zero-pad the final frame.
def finalize(self) -> None: ...
# Return the number of frames available to read.
@property
def available_frames(self) -> int: ...
# Read up to ``max_frames`` analyzed frames (consumes them).
def read_frames(self, max_frames: int) -> StreamFrames: ...
# Read up to ``max_frames`` frames as 8-bit quantized arrays.
def read_quantized_frames_u8(
self,
max_frames: int,
quantize_config: StreamQuantizeConfig | None = None,
) -> StreamFramesU8: ...
# Read up to ``max_frames`` frames as 16-bit quantized arrays.
def read_quantized_frames_i16(
self,
max_frames: int,
quantize_config: StreamQuantizeConfig | None = None,
) -> StreamFramesI16: ...
# Reset analyzer state for a new stream starting at ``start_sample``.
def reset(self, start_sample: int = 0) -> None: ...
# Read the current statistics and progressive estimate snapshot.
def stats(self) -> StreamStats: ...
# Return the total number of frames processed.
@property
def frame_count(self) -> int: ...
# Return the current stream time position in seconds.
@property
def current_time_sec(self) -> float: ...
# Return the configured input sample rate in Hz.
@property
def sample_rate(self) -> int: ...
# Set the expected total duration (s) for pattern-lock timing.
def set_expected_duration(self, duration_sec: float) -> None: ...
# Set a normalization gain applied to input samples.
def set_normalization_gain(self, gain: float) -> None: ...
# Set the A4 tuning reference (Hz) and rebuild the chroma filterbank.
def set_reference_hz(self, reference_hz: float) -> None: ...