Python Audio クラス API
Audio は libsonare Python パッケージのモノラルのサンプルバッファです。サンプルを一度読み込むか包んでおけば、解析、特徴量、ラウドネス、エフェクト、マスタリングの関数をそのメソッドとして呼べます。DecodedChannels は、モノラルへのダウンミックスではなくすべてのソースチャンネルが必要なときに decode_channels が返す型です。メソッドが包む関数は Python 解析 API、Python 特徴抽出 API、Python エフェクト API、Python メータリングと信号ヘルパー API、Python マスタリング API に、返されるレコードは Python 解析の型 と Python エフェクトの型 にあります。
Audio の作成
ソースごとに 4 つのコンストラクタがあります。Audio(handle, lib) 自体は内部用なので、クラスメソッドで作成してください。
| コンストラクタ | ソース |
|---|---|
Audio.from_file(path, channel_index=None) | ディスク上のファイル。既定のビルドでは WAV と MP3。-DSONARE_WITH_FFMPEG=ON でビルドすると、M4A/AAC/FLAC/OGG/Opus と、リンクした FFmpeg が扱えるその他のコンテナも読めます |
Audio.from_memory(data) | エンコード済みのオーディオバイト列。対応フォーマットは from_file と同じです |
Audio.from_buffer(samples, sample_rate) | 名目上 [-1.0, 1.0] のモノラルの浮動小数点サンプル列 |
Audio.file_num_channels(path) | コンストラクタではありません。デコードせずにファイルのソースチャンネル数を調べます |
Audio は 1 チャンネルしか持たないため、マルチチャンネルのソースはダウンミックスされます。チャンネルを保つには、from_file(path, channel_index=n) で 1 チャンネルずつ読み込む(file_num_channels と組み合わせます。1 回の読み込みでファイルを 1 回デコードするので、ステレオなら 2 回デコードします)か、decode_channels で全チャンネルを一度にデコードします。後者はソース本来のチャンネル順(5.1 は L R C LFE Ls Rs)のチャンネルプラナー配列を返します。
from_buffer は list、tuple、array.array、1 次元の NumPy 配列を受け取ります。マルチチャンネルの入力は先に downmix(channels, "mono")[0] で折りたたんでください。空のバッファや NaN・Inf を含むバッファは SonareValueError になります。存在しないファイルは FILE_NOT_FOUND の SonareError、デコードできないバイト列やファイルは DECODE_FAILED の SonareError になり、メッセージにはデコーダが挙げた理由が入ります。ファイルにないチャンネルや負の値を channel_index に指定すると SonareValueError です。
Audio クラス
# Wrapper around the SonareAudio opaque pointer.
class Audio:
def __init__(self, handle: ctypes.c_void_p, lib: ctypes.CDLL) -> None: ...
# Load audio from a file path.
@classmethod
def from_file(cls, path: str, channel_index: int | None = None) -> Audio: ...
# Return the source channel count encoded in an audio file.
@classmethod
def file_num_channels(cls, path: str) -> int: ...
# Create audio from a float sample buffer.
@classmethod
def from_buffer(cls, samples: Sequence[float] | list[float], sample_rate: int) -> Audio: ...
# Create audio from in-memory encoded audio bytes.
@classmethod
def from_memory(cls, data: bytes) -> Audio: ...
# Return audio samples as a ``float32`` numpy array.
@property
def data(self) -> np.ndarray: ...
# Return the number of audio samples.
@property
def length(self) -> int: ...
# Return the sample rate in Hz.
@property
def sample_rate(self) -> int: ...
# Return the audio duration in seconds.
@property
def duration_sec(self) -> float: ...
# Detect BPM (tempo).
def detect_bpm(
self,
*,
bpm_min: float | None = None,
bpm_max: float | None = None,
) -> float | None: ...
# Detect musical key and the tuning its chroma was built with.
def detect_key(
self,
n_fft: int = 2048,
hop_length: int = 512,
use_hpss: bool = False,
loudness_weighted: bool = False,
chroma_high_pass_hz: float = 80.0,
modes: Sequence[KeyMode] | str | None = None,
profile: KeyProfile | None = None,
genre_hint: GenreHint | None = None,
tuning_cents: float | str = 'auto',
) -> KeyDetection: ...
# Return ranked musical key candidates; ``tuning_cents`` is as for :meth:`detect_key`.
def detect_key_candidates(
self,
n_fft: int = 2048,
hop_length: int = 512,
use_hpss: bool = False,
loudness_weighted: bool = False,
chroma_high_pass_hz: float = 80.0,
modes: Sequence[KeyMode] | str | None = None,
profile: KeyProfile | None = None,
genre_hint: GenreHint | None = None,
tuning_cents: float | str = 'auto',
) -> list[KeyCandidate]: ...
# Detect beat times in seconds.
def detect_beats(
self,
*,
bpm_min: float | None = None,
bpm_max: float | None = None,
) -> np.ndarray: ...
# Detect downbeat times in seconds.
def detect_downbeats(self) -> np.ndarray: ...
# Detect onset times in seconds as a float32 array.
def detect_onsets(self) -> np.ndarray: ...
# Run full music analysis, forwarding to the module-level :func:`libsonare.analyze`.
def analyze(self, **kwargs: Any) -> AnalysisResult: ...
# Analyze BPM with candidates and intermediate curves.
def analyze_bpm(
self,
bpm_min: float | None = None,
bpm_max: float | None = None,
n_fft: int = 2048,
hop_length: int = 512,
max_candidates: int = 5,
) -> BpmAnalysisResult: ...
# Analyze RT60, EDT, and clarity metrics treating this audio as an impulse response.
def analyze_impulse_response(self, n_octave_bands: int = 6) -> AcousticResult: ...
# Estimate blind RT60 from this audio (EDT and clarity read as NaN).
def detect_acoustic(
self,
n_octave_bands: int = 6,
n_third_octave_subbands: int = 24,
min_decay_db: float = 30.0,
noise_floor_margin_db: float = 10.0,
) -> AcousticResult: ...
# Analyze rhythm primitives.
def analyze_rhythm(
self,
bpm_min: float | None = None,
bpm_max: float | None = None,
start_bpm: float = 120.0,
n_fft: int = 2048,
hop_length: int = 512,
) -> RhythmResult: ...
# Analyze dynamics and loudness primitives.
def analyze_dynamics(
self,
window_sec: float = 0.4,
hop_length: int = 512,
compression_threshold_db: float = 6.0,
) -> DynamicsResult: ...
# Analyze timbre and spectral-shape primitives.
def analyze_timbre(
self,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
n_mfcc: int = 13,
window_sec: float = 0.5,
) -> TimbreResult: ...
# Detect chord segments.
def detect_chords(
self,
min_duration_sec: float = 0.3,
smoothing_window_sec: float = 2.0,
threshold: float = 0.5,
use_triads_only: bool = True,
n_fft: int = 2048,
hop_length: int = 512,
use_beat_sync: bool = True,
use_hmm: bool = True,
hmm_beam_width: int = 24,
use_key_context: bool = False,
key_root: PitchClass = PitchClass.C,
key_mode: KeyMode = 'major',
detect_inversions: bool = False,
chroma_method: str = 'cqt',
tuning_cents: float | str = 'auto',
) -> ChordAnalysisResult: ...
# Perform harmonic-percussive source separation.
def hpss(
self,
kernel_harmonic: int = 31,
kernel_percussive: int = 31,
with_residual: bool = False,
) -> HpssResult: ...
# Extract the harmonic component.
def harmonic(self) -> np.ndarray: ...
# Extract the percussive component.
def percussive(self) -> np.ndarray: ...
# Time-stretch audio without changing pitch; ``speed_ratio`` > 1 shortens.
def time_stretch(self, speed_ratio: float) -> np.ndarray: ...
# Shift the pitch of audio by ``pitch_semitones`` (positive = up).
def pitch_shift(self, pitch_semitones: float) -> np.ndarray: ...
# Pitch-correct audio from a current MIDI note to a target MIDI note.
def pitch_correct_to_midi(self, current_midi: float, target_midi: float) -> np.ndarray: ...
# Time-stretch a single note region without changing pitch.
def note_stretch(
self,
onset_sample: int | None = None,
offset_sample: int | None = None,
stretch_ratio: float = 1.0,
*,
onset_sec: float | None = None,
offset_sec: float | None = None,
) -> np.ndarray: ...
# Move a note region.
def note_move(
self,
onset_sample: int | None = None,
offset_sample: int | None = None,
target_onset_sample: int | None = None,
*,
onset_sec: float | None = None,
offset_sec: float | None = None,
target_onset_sec: float | None = None,
) -> np.ndarray: ...
# Apply a voice-change effect with independent pitch and formant control.
def voice_change(
self,
pitch_semitones: float = 0.0,
formant_factor: float = 1.0,
formant_mode: str = 'relative',
) -> np.ndarray: ...
# Apply the integrated realtime voice changer chain offline.
def realtime_voice_changer_render(
self,
*,
config: VoicePresetId | RealtimeVoiceChangerPreset | RealtimeVoiceChangerConfig | None = 'neutralMonitor',
) -> np.ndarray: ...
# Normalize the peak or RMS level; see :func:`libsonare.normalize`.
def normalize(
self,
*,
mode: NormalizeMode = 'peak',
target_db: float | None = None,
) -> np.ndarray: ...
# Apply mastering loudness normalization with a true-peak ceiling.
def mastering(
self,
target_lufs: float = -14.0,
ceiling_dbtp: float = -1.0,
true_peak_oversample: int | None = None,
release_ms: float | None = None,
apply_gain_at_input_rate: bool = False,
) -> MasteringResult: ...
# Apply a named mastering processor.
def mastering_apply_processor(
self,
processor: str,
params: dict[str, float | int | bool | str] | None = None,
) -> MasteringResult: ...
# Master this audio with a named preset, a chain of overrides, or both.
def master_audio(
self,
*,
preset: str | None = None,
overrides: MasteringChainConfigInput | None = None,
on_progress: Callable[[float, str], None] | None = None,
cancel: Callable[[], bool] | None = None,
) -> MasteringChainResult: ...
# Trim silence from the beginning and end.
def trim(self, threshold_db: float = -60.0) -> np.ndarray: ...
# Compute the short-time Fourier transform.
def stft(
self,
n_fft: int = 2048,
hop_length: int = 512,
*,
db: bool = False,
phase: bool = False,
) -> StftResult: ...
# Compute a Mel spectrogram.
def mel_spectrogram(
self,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
) -> MelSpectrogramResult: ...
# Compute Mel-frequency cepstral coefficients.
def mfcc(
self,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
n_mfcc: int = 20,
) -> MfccResult: ...
# Compute chroma features.
def chroma(self, n_fft: int = 2048, hop_length: int = 512) -> ChromaResult: ...
# Compute NNLS chroma as a float32 array of shape ``(12, n_frames)``.
def nnls_chroma(self) -> np.ndarray: ...
# Compute the onset strength envelope (float32, one value per frame).
def onset_strength(
self,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
) -> np.ndarray: ...
# Compute integrated/momentary/short-term LUFS and loudness range.
def lufs(self) -> LufsResult: ...
# Compute the per-block momentary LUFS time series as a float32 array.
def momentary_lufs(self) -> np.ndarray: ...
# Compute the per-block short-term LUFS time series as a float32 array.
def short_term_lufs(self) -> np.ndarray: ...
# Compute the spectral centroid per frame as a float32 array.
def spectral_centroid(self, n_fft: int = 2048, hop_length: int = 512) -> np.ndarray: ...
# Compute the spectral bandwidth per frame as a float32 array.
def spectral_bandwidth(
self,
n_fft: int = 2048,
hop_length: int = 512,
p: float = 2.0,
) -> np.ndarray: ...
# Compute the spectral rolloff per frame as a float32 array.
def spectral_rolloff(
self,
n_fft: int = 2048,
hop_length: int = 512,
roll_percent: float = 0.85,
) -> np.ndarray: ...
# Compute the spectral flatness per frame as a float32 array.
def spectral_flatness(self, n_fft: int = 2048, hop_length: int = 512) -> np.ndarray: ...
# Compute the zero-crossing rate per frame as a float32 array.
def zero_crossing_rate(self, frame_length: int = 2048, hop_length: int = 512) -> np.ndarray: ...
# Compute the RMS energy per frame as a float32 array.
def rms_energy(self, frame_length: int = 2048, hop_length: int = 512) -> np.ndarray: ...
# Estimate fundamental frequency using the YIN algorithm.
def pitch_yin(
self,
frame_length: int = 2048,
hop_length: int = 512,
f0_min_hz: float = 65.0,
f0_max_hz: float = 2093.0,
threshold: float = 0.1,
) -> PitchResult: ...
# Estimate fundamental frequency using the pYIN algorithm.
def pitch_pyin(
self,
frame_length: int = 2048,
hop_length: int = 512,
f0_min_hz: float = 65.0,
f0_max_hz: float = 2093.0,
threshold: float = 0.1,
fill_na: bool = False,
) -> PitchResult: ...
# Resample audio to a different sample rate; returns a float32 array.
def resample(self, target_sample_rate: int) -> np.ndarray: ...
# Sample-peak in dBFS over the buffer.
def peak_db(self) -> float: ...
# RMS level in dBFS over the buffer.
def rms_db(self) -> float: ...
# DC offset (mean) of the buffer in linear amplitude.
def dc_offset(self) -> float: ...
# Crest factor in dB (peak_db - rms_db).
def crest_factor_db(self) -> float: ...
# Fraction of analysis frames whose RMS is below ``threshold_db``.
def silence_ratio(
self,
threshold_db: float = -45.0,
frame_length: int = 1024,
hop_length: int = 256,
) -> float: ...
# Inter-sample (true) peak in dBFS.
def true_peak_dbtp(self, oversample_factor: int | None = None) -> float: ...
# Detect clipped runs; see :func:`libsonare.metering_detect_clipping`.
def detect_clipping(
self,
threshold_db: float | None = None,
min_region_samples: int | None = None,
) -> ClippingReport: ...
# Sliding-window dynamic range (high_percentile - low_percentile, in dB).
def dynamic_range(
self,
window_sec: float | None = None,
hop_sec: float | None = None,
low_percentile: float | None = None,
high_percentile: float | None = None,
) -> DynamicRangeReport: ...
# Welch-averaged magnitude / power / dB spectrum over the whole buffer.
def spectrum(
self,
n_fft: int | None = None,
apply_octave_smoothing: bool = False,
octave_fraction: int | None = None,
db_ref: float | None = None,
db_amin: float | None = None,
) -> SpectrumReport: ...
# True single-frame mono magnitude / power / dB spectrum (one Hann-windowed FFT).
def spectrum_frame(
self,
frame_offset: int = 0,
n_fft: int | None = None,
apply_octave_smoothing: bool = False,
octave_fraction: int | None = None,
db_ref: float | None = None,
db_amin: float | None = None,
) -> SpectrumReport: ...
# EBU R128 / Tech 3342 Loudness Range (LRA) in LU.
def ebur128_loudness_range_lu(self) -> float: ...
# Free the underlying audio resource.
def close(self) -> None: ...
# Return this audio; leaving the ``with`` block closes it.
def __enter__(self) -> Audio: ...
# Close the audio when the ``with`` block exits.
def __exit__(self, *args: object) -> None: ...data はネイティブのサンプルのコピーを float32 配列として返すため、close() より前に取り出した配列は閉じた後も有効です。length、sample_rate、duration_sec はバッファの属性を読みます。Audio を閉じた後に data やこれらを読んだり、メソッドを呼んだりすると、INVALID_STATE の SonareError になります。
Audio はコンテキストマネージャで、with ブロックを抜けると閉じます。
from libsonare import Audio
with Audio.from_file("music.mp3") as audio:
result = audio.analyze()メソッドの働き
解析、特徴量、ラウドネス、エフェクト、マスタリングの関数の多くはメソッドとしても用意されています。メソッドは samples と sample_rate をオブジェクトから補い、その後にその関数のオプションを取ります。つまり audio.detect_bpm(bpm_min=80) は detect_bpm(audio.data, audio.sample_rate, bpm_min=80) に相当します。各メソッドが残しているオプションは上の生成されたシグネチャで確認できます。戻り値は関数と同じレコード(AnalysisResult、StftResult、LufsResult、HpssResult、MasteringResult など)です。
detect_* の呼び出しはそれぞれ独自に解析を実行し、何もキャッシュしません。4 回呼べばパイプラインが 4 回走るので、すべてが必要なら analyze() を使ってください。detect_* 以外にも、個別の解析として analyze_bpm、analyze_rhythm、analyze_dynamics、analyze_timbre、analyze_impulse_response、detect_acoustic と、位置引数で呼ぶ detect_chords があります。メソッドを持たない個別の関数(analyze_sections、analyze_melody、cqt、vqt)には audio.data と audio.sample_rate を渡してください。
デコードされたチャンネル
# Result of :func:`decode_channels`.
@dataclass(frozen=True, slots=True, eq=False)
class DecodedChannels:
sample_rate: int
channels: np.ndarraychannels は (num_channels, frames) の形をしたチャンネルプラナーの float32 配列で、ソース本来のチャンネル順です。複数チャンネルを受け取るエントリポイントが取る形と同じです。sample_rate はデコードされたオーディオのレートで、単位は Hz です。decode_channels は、空のバイト列、デコードできない入力、有限でないサンプル、サポート範囲外のサンプルレートに対して SonareError を送出します。
エンコードとタグ
encode_audio はチャンネル平面のサンプルを、WAV、FLAC、MP3、OGG、Opus、M4A の形式トークンでメモリ内バッファに書き込みます。ビルドに任意エンコーダーがない形式は SonareError(NOT_SUPPORTED)になります。タグは文字列から文字列へのマッピングで指定します。形式の既定値を使う場合は bit_depth を省略し、エンコーダーの既定品質を使う場合は quality を省略します。チャンネル長の不一致と bit depth 0 は SonareValueError、マッピング以外のタグは TypeError になります。read_audio_tags はサンプルをデコードせずに正規化したテキストタグを返します。data が bytes でなければ TypeError、未対応または不正な音声バイト列ならコード付きの SonareError になります。
from libsonare import encode_audio, read_audio_tags
encoded = encode_audio([[0.0, 0.1, -0.1, 0.0]], 48000, "wav", tags={"title": "example"})
assert read_audio_tags(encoded)["title"] == "example"# Encode channel-planar samples into an in-memory audio file.
def encode_audio(
channels: Sequence[Sequence[float] | np.ndarray] | np.ndarray,
sample_rate: int,
format: str,
*,
tags: Mapping[str, str] | None = None,
bit_depth: int | None = None,
quality: float | None = None,
) -> bytes: ...
# Read normalized container tags from audio bytes without decoding samples.
def read_audio_tags(data: bytes) -> dict[str, str]: ...