Python ストリーミング API
libsonare Python パッケージのブロック単位のプロセッサで、リアルタイムボイスチェンジャー、StreamingRetune、ストリーミング EQ を扱います。どれもブロックをまたいで状態を保持し、ネイティブメモリを所有し、close() か with ブロックで解放します(ネイティブハンドルの解放)。逐次処理の StreamAnalyzer はストリーミング解析 API、ストリーミングマスタリングチェーンは Python マスタリング API、映画音声の再生レンダラーは Python 再生 API にあります。
リアルタイムボイスチェンジャー
RealtimeVoiceChanger は、WASM / Node ネイティブと同じプリセット式のライブ音声チェーンを Python から扱うオブジェクトです。ハイパス、ゲート、リチューン、フォルマント、EQ、コンプレッサー、ディエッサー、リバーブ、リミッターの状態をブロック間で保持します。マイク入力やストリームを処理する場合は、オフラインの voice_change(...) ではなくこちらを使います。
import json
import libsonare as sonare
print(sonare.realtime_voice_changer_preset_names())
print(sonare.voice_changer_abi_version()) # ネイティブ POD 設定の ABI バージョン
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") # 正規化済み 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)
# 同じリアルタイムチェーンを使う単発のレンダリング。
processed = sonare.realtime_voice_changer_render(vocal, 48000, config="softWhisper")現在のプリセット ID には neutralMonitor、brightIdol、softWhisper、deepNarrator、robotMascot、darkVillain、hardTune、robotMonotone、choirHarmony、vocoderStrings、megaphone、radioVoice があります。組み込み ID はここに示した厳密な文字列です。カスタムマッピングはプリセット JSON のバリデーターを通し、dsp または macros のどちらか一方だけを持つ必要があります。形式が正しくないものは拒否されます。
JSON ではなく解決済みの POD 設定が必要な場合は、realtime_voice_changer_preset_config(preset) を使います。VoicePresetId で指定した組み込みプリセットの、正規化済み RealtimeVoiceChangerConfig を返します。インデックスは TypeError になるので、先に voice_character_preset_id(index) で ID にしてください。
formant_mode(既定は "relative"、もうひとつは "absolute")はボイスチェンジャーの作成時に固定されます(プリセットキーは dsp.formant.mode)。voice_engine="grain" の絶対モードでは、レイテンシが解析 1 フレーム分増えます。計算したワープが実現できない設定は拒否されます。既定の PSOLA エンジンでは、モードによるレイテンシの増加はありません。コンストラクターでも後からの設定更新でも、非有限または範囲外の設定値は名前を挙げて拒否され、ボイスチェンジャーは以前の設定を保ちます。ステレオ入力では、作成時に num_channels=2 を指定して process_planar([left, right]) または process_interleaved(samples, num_channels) を呼びます。StreamingRetune(pitch_semitones=, mix=, grain_size_samples=) は、リチューン段だけをブロック単位で単独実行します(先に prepare(sample_rate, max_block_size) を呼びます)。
プリセット関数
realtime_voice_changer_preset_names() は組み込みプリセットを列挙し、realtime_voice_changer_preset_json(name) はひとつのプリセットの JSON テキストを返します(不明な名前では SonareError)。validate_realtime_voice_changer_preset_json(json_text) はプリセットの JSON テキストを検証し、例外を送出する代わりに結果を dict で返します。
# 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: ...ストリーミング EQ API
StreamingEqualizer は、ネイティブのブロック処理 EQ エンジンを Python から扱うオブジェクトです。ライブプレビュー、プロセッサ UI、マスタリングチェーンを組まずにソースの音色をリファレンスへ寄せる用途に使えます。
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)
# バッファの長さは異なっていてよく、リファレンスは独自のレートでも構いません
eq.match(source_samples, reference_samples, max_bands=8, reference_sample_rate=44100)
out = eq.process_mono(input_block)
snapshot = eq.spectrum()バンドは Python の辞書で渡します(JSON テキストは先に json.loads で変換します)。set_phase_mode(...) は zero、natural、linear の名前を受け取ります。出力ゲイン/パン、ダイナミックバンド用のサイドチェイン入力、process_stereo(...)、spectrum()、latency_samples、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: ...ストリーミングリチューン
StreamingRetune は、ブロック単位で動くモノラルのピッチシフターです(グレインのオーバーラップ加算)。オフラインの pitch_shift に対応するストリーミング版です。状態は process_mono(...) の呼び出しをまたいで保持されるので、連続するブロックは継ぎ目なくつながります。処理の前に prepare(...) を呼ぶ必要があります。pitch_semitones は有限で [-24, 24] の範囲、mix は有限で [0, 1] の範囲でなければならず、範囲外の値は 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: ...ストリーミング解析 API
StreamAnalyzer は、音声がブロック単位で届く場面で使います。たとえば、ライブ入力、コールバックループ、一度に全体解析したくない長いファイル、フレーム単位の可視化です。
内部バッファに音声を蓄積しながら、mel/chroma/onset/spectral フレームを出力します。BPM、キー、コード、小節、進行パターンの推定も定期的に更新します。
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 はリニアのメルパワーで形状は (n_mels, n_frames)。compute_mel がオフなら None
# frames.chroma の形状は (n_chroma, n_frames)。compute_chroma がオフなら None
estimate = stream.stats().estimate
if estimate.bpm is not None:
print(estimate.bpm, estimate.bpm_confidence)アナライザーはキーワード引数で設定します(sample_rate 以外は任意)。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、window が使え、省略したオプションにはライブラリの既定値が入ります。
UI 転送量を抑える場合は、read_frames(max_frames) の代わりに量子化読み出しを使います。
| メソッド | 変わる点 |
|---|---|
read_quantized_frames_u8(max_frames, quantize_config?) | 特徴量配列を符号なし 8 ビット値へ量子化します(StreamFramesU8)。 |
read_quantized_frames_i16(max_frames, quantize_config?) | 特徴量配列を符号付き 16 ビット値へ量子化します(StreamFramesI16)。 |
quantize_config は任意の StreamQuantizeConfig(libsonare からエクスポート)で、既定より大幅に大きい/小さいストリームに合わせて量子化レンジを広げます。省略すると既定値を使います。フィールドと既定値は mel_db_min=-80.0、mel_db_max=0.0、onset_max=50.0、rms_max=1.0、centroid_max=11025.0 です。量子化器は正規化値を [0, 1] にクランプするため、このレンジを外れた信号は警告なしに端点で飽和します。これは JS/WASM ストリーミングドキュメントの StreamQuantizeConfig に対応します。
3 つの読み出しはいずれも timestamps_sec を float で返します。外部の音声クロックと同期したい場合は、process(samples, start_sample) でチャンク開始位置を明示してください。
start_sample を渡した process が受け付けるのは連続したオフセットだけです。ギャップやシークの後、またはオフセットなしの process(samples) から切り替える前には、reset(start_sample) を呼んでから次のブロックを渡してください。max_progression_entries(既定 4096)はコード進行と小節進行をそれぞれ保持する上限です。最古の履歴が破棄された場合は、stats() の dropped_chord_progression_entries と dropped_bar_progression_entries で確認できます。NaN や Inf の入力が置き換えられたブロックの数は non_finite_discard_blocks に入ります。
StreamAnalyzer のシグネチャ
# 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: ...