Python 信号・変換 API
libsonare Python パッケージのテスト信号、構造解析、逆再構成、スケール量子化、単位変換、チャンネルと信号のユーティリティのリファレンスです。特徴抽出は Python 特徴抽出 API、メータリングとフレーミングのヘルパーは Python メータリングと信号ヘルパー API にあります。インストール、クイックスタート、その他の API ファミリーは Python API の索引ページを参照してください。
テスト信号・再構成・構造解析
import libsonare as sonare
# 決定的なテスト信号。アセットファイルは不要です。
sine = sonare.tone(frequency=440.0, sr=48000, duration=1.0)
sweep = sonare.chirp(fmin=100.0, fmax=8000.0, sr=48000, duration=2.0)
track = sonare.clicks(times=[0.0, 0.5, 1.0], sr=48000)
# 再構成とビンごとのピッチ候補
audio_again = sonare.griffin_lim(magnitude, sample_rate=48000) # magnitude: 2-D (n_bins, n_frames)
reassigned = sonare.reassigned_spectrogram(samples, sr=48000)
peaks = sonare.piptrack(samples, sr=48000)
delta = sonare.mel_delta(features) # features: 2-D (n_features, n_frames)
flux = sonare.spectral_flux(samples, sample_rate=48000)
backtracked = sonare.onset_backtrack(onset_frames, energy)
# モノフォニックの F0 トラックからノート区間を切り出す
pitch = sonare.pitch_pyin(samples, sample_rate=48000)
segments = sonare.note_segments(
pitch.f0,
frame_rate=48000 / 512,
voiced=pitch.voiced_flag,
min_note_ms=60.0,
)# Generate a sine tone as a float32 array.
def tone(
frequency: float = 440.0,
sr: int = 22050,
duration: float = 1.0,
phi: float = 0.0,
amplitude: float = 1.0,
) -> np.ndarray: ...
# Generate a linear or exponential chirp as a float32 array.
def chirp(
fmin: float = 440.0,
fmax: float = 880.0,
sr: int = 22050,
duration: float = 1.0,
linear: bool = False,
) -> np.ndarray: ...
# Generate decaying sine clicks at times in seconds as a float32 array.
def clicks(
times: Sequence[float] | list[float],
sr: int = 22050,
length: int | None = None,
click_freq: float = 1000.0,
click_duration: float = 0.1,
) -> np.ndarray: ...
# Return magnitude, reassigned times and reassigned frequencies per STFT bin.
def reassigned_spectrogram(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
ref_power: float = 1e-06,
fill_nan: bool = False,
) -> ReassignedSpectrogramResult: ...
# Return per-bin spectral pitch candidates and their peak magnitudes.
def piptrack(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
fmin: float = 150.0,
fmax: float = 4000.0,
threshold: float = 0.1,
) -> PiptrackResult: ...
# Compute first-order regression deltas of a feature matrix.
def mel_delta(features: npt.ArrayLike, width: int = 9) -> np.ndarray: ...
# Compute the unsigned L1 spectral-flux envelope as a float32 array.
def spectral_flux(
samples: Sequence[float] | list[float],
sample_rate: int,
n_fft: int = 2048,
hop_length: int = 512,
lag: int = 1,
) -> np.ndarray: ...
# Backtrack onset event indices to local energy minima.
def onset_backtrack(
events: Sequence[int] | list[int],
energy: Sequence[float] | list[float],
) -> np.ndarray: ...
# Segment a monophonic F0 track into stable note regions.
def note_segments(
f0_hz: Sequence[float] | list[float],
frame_rate: float,
*,
voiced: Sequence[int] | list[int] | None = None,
voiced_prob: Sequence[float] | list[float] | None = None,
segmentation_threshold_cents: float | None = None,
min_note_ms: float | None = None,
reference_hz: float | None = None,
voiced_threshold: float | None = None,
) -> list[NoteSegment]: ...渡すのは voiced_flag であって voiced_prob ではありません
note_segments はフレームごとの有声判定を voiced(フラグ。0 以外が有声)で受け取るので、pitch_pyin の voiced_flag をそのまま渡してください。代わりに voiced_prob を渡すこともでき、その場合は voiced_threshold(既定 0.5)で二値化されます。どちらか一方が必須です。voiced_prob はそのフレームの有声観測量であり、解析窓に何周期分収まるかに依存するため、確信度を表すのではなく F0 とともに上昇します。frame_length=2048、48 kHz では、定常的な 3 倍音のトーンで C2 の平均が 0.1 をはるかに下回り、C5 で 0.5 前後になります。そのため低音楽器や低い男声のトラックを固定しきい値で処理すると、例外は出ないまま空のリストが返ります。連続的な有声度で区切りたい場合は voiced_threshold がもう一方の調整点です。
自己類似度系の関数は、JavaScript の segment* と同じ segment_ 接頭辞を持ちます。
# Return column-wise cross-similarity (``librosa.segment.cross_similarity``).
def segment_cross_similarity(
x: npt.ArrayLike,
y: npt.ArrayLike,
k: int | None = None,
metric: Literal['cosine', 'euclidean'] = 'cosine',
mode: Literal['connectivity', 'affinity'] = 'connectivity',
) -> np.ndarray: ...
# Return a self-similarity recurrence matrix (``librosa.segment.recurrence_matrix``).
def segment_recurrence_matrix(
data: npt.ArrayLike,
k: int | None = None,
width: int = 1,
sym: bool = False,
metric: Literal['cosine', 'euclidean'] = 'euclidean',
mode: Literal['connectivity', 'affinity'] = 'connectivity',
) -> np.ndarray: ...
# Convert a square recurrence matrix to a lag-by-time matrix.
def segment_recurrence_to_lag(recurrence: npt.ArrayLike, pad: bool = True) -> np.ndarray: ...
# Convert a lag matrix back to an ``(n, n)`` recurrence matrix.
def segment_lag_to_recurrence(lag: npt.ArrayLike) -> np.ndarray: ...
# Enhance diagonal paths in a square recurrence matrix of shape ``(n, n)``.
def segment_path_enhance(
recurrence: npt.ArrayLike,
win: int,
max_ratio: int = 2,
min_ratio: int | None = None,
n_filters: int = 7,
) -> np.ndarray: ...
# Refine frame boundaries by clustering each parent segment.
def segment_subsegment(
data: npt.ArrayLike,
boundaries: Sequence[int] | list[int],
n_segments: int = 4,
) -> np.ndarray: ...
# Cluster feature columns and return one label per column as an int32 array.
def segment_agglomerative(
data: npt.ArrayLike,
k: int,
linkage: Literal['average', 'single', 'complete', 'ward'] = 'average',
) -> np.ndarray: ...| Python | JavaScript |
|---|---|
segment_cross_similarity | segmentCrossSimilarity(...) |
segment_recurrence_matrix | segmentRecurrenceMatrix(...) |
segment_recurrence_to_lag | segmentRecurrenceToLag(...) |
segment_lag_to_recurrence | segmentLagToRecurrence(...) |
segment_path_enhance | segmentPathEnhance(...) |
segment_subsegment | segmentSubsegment(...) |
segment_agglomerative | segmentAgglomerative(...) |
segment_recurrence_to_lag は (n, n) の recurrence 行列を受け取り、librosa の lag-by-time 配置(lag[l, i] = rec[(i + l) % n_lags, i])を返します。パディングあり(既定)は 2n × n、pad=False は n × n です。segment_lag_to_recurrence はどちらの高さも受け取り(n_lags は n か 2 * n)、(n, n) の行列を返します。JavaScript では segmentRecurrenceToLag の pad: true に当たります。
ピッチ・特徴量の用語: YIN/pYIN・ゼロ交差率・MIDI ノート番号
- YIN / pYIN:単音の基本周波数(体感ピッチ)を推定するアルゴリズムです。YIN は自己相関を使い、pYIN は確率的な平滑化を加えてピッチラインを時間方向に安定させます。いずれも和音ではなく一度に 1 音を追跡します。
- ゼロ交差率(ZCR):波形が 1 フレームあたり何回ゼロを横切るか。高いとノイズ的・高域的(シンバル、摩擦音)、低いと滑らかで音程的な音を表します。
- MIDI ノート番号:ピッチを表す整数で、A4 = 69、中央 C = 60、半音ごとに ±1 です。下の
hz_to_midi/midi_to_hzが Hz とこの尺度を変換します。
逆再構成関数
メルスペクトログラムや MFCC 行列から、スペクトルや音声を再構成します。位相は Griffin-Lim で推定するため、元音声への完全な往復変換ではありません。詳細は 逆変換特徴量 を参照してください。行列入力は (バンド数またはビン数, n_frames) の 2 次元配列です。
# Reconstruct audio from an STFT magnitude of shape ``(n_bins, n_frames)``.
def griffin_lim(
magnitude: npt.ArrayLike,
sample_rate: int,
n_fft: int | None = None,
hop_length: int | None = None,
n_iter: int = 32,
momentum: float = 0.99,
) -> np.ndarray: ...
# Approximate inverse of a Mel filterbank (Mel power -> STFT magnitude).
def mel_to_stft(
mel: npt.ArrayLike,
sr: int = 22050,
n_fft: int = 2048,
fmin: float = 0.0,
fmax: float | None = None,
htk: bool = False,
) -> np.ndarray: ...
# Reconstruct audio from a Mel spectrogram via Griffin-Lim.
def mel_to_audio(
mel: npt.ArrayLike,
sr: int = 22050,
n_fft: int = 2048,
hop_length: int | None = None,
fmin: float = 0.0,
fmax: float | None = None,
n_iter: int = 32,
htk: bool = False,
) -> np.ndarray: ...
# Invert MFCC coefficients back to a Mel power spectrogram.
def mfcc_to_mel(
coefficients: npt.ArrayLike,
n_mels: int = 128,
lifter: float = 0.0,
) -> np.ndarray: ...
# Reconstruct audio directly from MFCC via Mel inversion + Griffin-Lim.
def mfcc_to_audio(
coefficients: npt.ArrayLike,
n_mels: int = 128,
sr: int = 22050,
n_fft: int = 2048,
hop_length: int | None = None,
fmin: float = 0.0,
fmax: float | None = None,
n_iter: int = 32,
htk: bool = False,
lifter: float = 0.0,
) -> np.ndarray: ...
# Reconstruct mono audio from a CQT magnitude via Griffin-Lim.
def cqt_to_audio(
magnitude: npt.ArrayLike,
sample_rate: int,
hop_length: int = 512,
fmin_hz: float = 32.70319566257483,
bins_per_octave: int = 12,
n_iter: int = 32,
) -> np.ndarray: ...
# Reconstruct mono audio from a VQT magnitude via Griffin-Lim.
def vqt_to_audio(
magnitude: npt.ArrayLike,
sample_rate: int,
hop_length: int = 512,
fmin_hz: float = 32.70319566257483,
bins_per_octave: int = 12,
gamma: float | None = None,
n_iter: int = 32,
) -> np.ndarray: ...| 関数 | 説明 |
|---|---|
griffin_lim | STFT 振幅行列 (n_bins, n_frames) から音声を復元します。n_iter の既定は 32、momentum の既定は 0.99 |
mel_to_stft | メルスペクトログラム (n_mels, n_frames) からリニア STFT 振幅 (n_bins, n_frames) |
mel_to_audio | メルスペクトログラムから音声(Griffin-Lim) |
mfcc_to_mel | MFCC 係数 (n_mfcc, n_frames) からメルパワースペクトログラム。lifter は順方向の mfcc(...) と揃えます |
mfcc_to_audio | MFCC 係数から音声 |
cqt_to_audio | CQT 振幅行列 (n_bins, n_frames) から音声(Griffin-Lim) |
vqt_to_audio | VQT 振幅行列 (n_bins, n_frames) から音声(Griffin-Lim) |
fmin の既定は 0.0、fmax の既定はナイキスト周波数、n_iter の既定は 32 です。往復変換の整合性を保つため、sr/n_fft/fmin/fmax/htk は順変換で使った値と同じにしてください。mel_spectrogram(...) や mfcc(...) の結果はこれらを属性として持っています。
istft は同じ (n_bins, n_frames) 形状の magnitude 行列と phase 行列から、centered audio を再構成します。n_fft を省略すると行数から推定し、hop_length は max(1, n_fft // 4) になり、戻り値は 1 次元の float32 波形です。形状の不一致と length_samples 0 は SonareValueError として拒否されます。自然な出力長を使う場合は length を省略します。
import numpy as np
from libsonare import istft
waveform = istft(
np.ones((65, 4), dtype=np.float32),
np.zeros((65, 4), dtype=np.float32),
n_fft=128,
hop_length=32,
)
assert waveform.shape == (96,)
assert waveform.dtype == np.float32# Reconstruct centered audio from STFT magnitude and phase matrices.
def istft(
magnitude: npt.ArrayLike,
phase: npt.ArrayLike,
n_fft: int | None = None,
hop_length: int | None = None,
*,
length_samples: int | None = None,
) -> np.ndarray: ...スケール量子化
ピッチ補正ターゲットを構築するための 12-TET スケールヘルパーです。
mode_mask は 12 ビットのマスクです。ビット i が、root(PitchClass、C = 0)を基準とした i 番目のピッチクラスを有効化します。自然な長調は 0b101010110101 です。
scale_reference_midi はチューニング基準音です。A4 = 69 にするには 0.0 を渡します。pitch_correct_to_midi(...) と組み合わせると、最も近いスケール構成音へリチューンできます。
# Return the 12-bit scale mask of a mode.
def scale_mask_for_mode(root: int, mode: KeyMode) -> int: ...
# Snap a (possibly fractional) MIDI number to the nearest enabled pitch class.
def scale_quantize_midi(
root: int,
mode_mask: int,
midi: float,
scale_reference_midi: float | None = None,
) -> float: ...
# Return the correction (quantized - input) in semitones.
def scale_correction_semitones(
root: int,
mode_mask: int,
midi: float,
scale_reference_midi: float | None = None,
) -> float: ...
# Return True if pitch_class (0..11) is enabled by mode_mask relative to root.
def scale_pitch_class_enabled(root: int, mode_mask: int, pitch_class: int) -> bool: ...| 関数 | 説明 |
|---|---|
scale_mask_for_mode | モードの 12 ビットマスクを返します。"major"、"minor"(自然短音階)、"dorian" などの KeyMode 文字列を指定します。文字列以外は TypeError、未知の文字列は SonareValueError になります。 |
scale_quantize_midi | 小数を含む MIDI 番号を最も近い有効なピッチクラスへ丸める |
scale_correction_semitones | 補正量(量子化後 − 入力)をセミトーンで返す |
scale_pitch_class_enabled | pitch_class(0..11)が root を基準に有効か |
変換関数
# Convert frequency in Hz to Mel scale.
def hz_to_mel(hz: float) -> float: ...
# Convert Mel scale value to frequency in Hz.
def mel_to_hz(mel: float) -> float: ...
# Convert frequency in Hz to MIDI note number.
def hz_to_midi(hz: float) -> float: ...
# Convert MIDI note number to frequency in Hz.
def midi_to_hz(midi: float) -> float: ...
# Convert frequency in Hz to note name (e.g.
def hz_to_note(hz: float) -> str: ...
# Convert note name (e.g.
def note_to_hz(note: str) -> float: ...
# Convert frame count to time in seconds.
def frames_to_time(frames: int, sr: int = 22050, hop_length: int = 512) -> float: ...
# Convert time in seconds to frame count.
def time_to_frames(time_sec: float, sr: int = 22050, hop_length: int = 512) -> int: ...
# Convert frame count to sample index.
def frames_to_samples(frames: int, hop_length: int = 512, n_fft: int | None = None) -> int: ...
# Convert sample index to frame count.
def samples_to_frames(samples: int, hop_length: int = 512, n_fft: int | None = None) -> int: ...
# Convert power values to dB; returns a float32 array shaped like ``values``.
def power_to_db(
values: Sequence[float] | list[float],
ref: float = 1.0,
amin: float = 1e-10,
top_db: float = 80.0,
) -> np.ndarray: ...
# Convert amplitude values to dB; returns a float32 array shaped like ``values``.
def amplitude_to_db(
values: Sequence[float] | list[float],
ref: float = 1.0,
amin: float = 1e-05,
top_db: float = 80.0,
) -> np.ndarray: ...
# Convert dB values back to power; returns a float32 array shaped like ``values``.
def db_to_power(values: Sequence[float] | list[float], ref: float = 1.0) -> np.ndarray: ...
# Convert dB values back to amplitude; returns a float32 array shaped like ``values``.
def db_to_amplitude(values: Sequence[float] | list[float], ref: float = 1.0) -> np.ndarray: ...| 関数 | 説明 |
|---|---|
hz_to_mel | ヘルツ → Mel スケール |
mel_to_hz | Mel スケール → ヘルツ |
hz_to_midi | ヘルツ → MIDI ノート番号 |
midi_to_hz | MIDI ノート番号 → ヘルツ |
hz_to_note | ヘルツ → 音名(例: "A4")。hz が有限でも正でもなければ SonareValueError |
note_to_hz | 音名 → ヘルツ。名前が解釈できない、またはオクターブが -1〜9 の範囲外なら SonareValueError |
frames_to_time | フレームインデックス → 秒 |
time_to_frames | 秒 → フレームインデックス |
frames_to_samples | フレームインデックス → サンプルインデックス(librosa.frames_to_samples) |
samples_to_frames | サンプルインデックス → フレームインデックス(librosa.samples_to_frames) |
power_to_db | パワー → dB(librosa.power_to_db) |
amplitude_to_db | 振幅 → dB(librosa.amplitude_to_db) |
db_to_power | dB → パワー |
db_to_amplitude | dB → 振幅 |
チャンネルと信号のユーティリティ
# Decode audio bytes once and keep every source channel.
def decode_channels(data: bytes) -> DecodedChannels: ...
# Downmix channels to a narrower layout with the ITU-R BS.775 rule.
def downmix(
channels: Sequence[Sequence[float] | np.ndarray] | np.ndarray,
target_layout: ChannelLayout,
*,
normalize: bool = False,
include_lfe: bool = False,
) -> np.ndarray: ...
# Apply a cosine fade-in and fade-out to mono audio.
def fade(
samples: Sequence[float] | list[float],
sample_rate: int,
*,
fade_in_sec: float = 0.0,
fade_out_sec: float = 0.0,
) -> np.ndarray: ...
# Filter mono audio with a biquad, or a cascade of two for order 4.
def biquad_filter(
samples: Sequence[float] | list[float],
sample_rate: int,
*,
type: BiquadFilterType,
order: int = 2,
zero_phase: bool = False,
cutoff_hz: float | None = None,
center_hz: float | None = None,
bandwidth_hz: float | None = None,
) -> np.ndarray: ...| 関数 | 説明 |
|---|---|
decode_channels | エンコード済みの音声バイト列を 1 回デコードし、すべてのソースチャンネルを、チャンネルごとに並んだ形状 (num_channels, frames) の float32 配列として保持します。Audio.from_memory はマルチチャンネルのソースをモノラルに畳み込みます |
downmix | ITU-R BS.775 の規則でチャンネルをより少ないレイアウト("mono"、"stereo"、"5.1"、"7.1")へダウンミックスします。センターとサラウンドは -3 dB でフロントのペアに入り、LFE は include_lfe=True でない限り捨てられます。normalize=True でない限り畳み込み結果は正規化されません。アップミックスは拒否されます |
fade | モノラル音声にコサインのフェードイン(fade_in_sec)とフェードアウト(fade_out_sec)をかけます。長さは入力の範囲に収められ、0 ならその端はそのままです |
biquad_filter | モノラル音声をバイクアッドで(order=4 では 2 段のカスケードで)フィルタリングします。"highPass" と "lowPass" は cutoff_hz を、"bandPass" と "notch" は center_hz と bandwidth_hz を読みます。そのタイプが読まない周波数は None のままにする必要があります。zero_phase=True は前向きと後ろ向きに通して位相のずれを打ち消します |
単位変換
from libsonare import hz_to_mel, mel_to_hz, hz_to_midi, midi_to_hz
from libsonare import hz_to_note, note_to_hz, frames_to_time, time_to_frames
hz_to_mel(440.0) # → 6.6(Slaney メルスケール)
mel_to_hz(6.6) # → 440.0
hz_to_midi(440.0) # → 69.0
midi_to_hz(69.0) # → 440.0
hz_to_note(440.0) # → "A4"
note_to_hz("A4") # → 440.0
frames_to_time(100, sr=22050, hop_length=512) # → 秒
time_to_frames(2.32, sr=22050, hop_length=512) # → フレームインデックス