Python Feature Extraction API
Feature extraction in the libsonare Python package: spectrogram, spectral, pitch, tuning, constant-Q, chroma, decomposition, onset-strength and loudness features. Audio and the analysis functions are on Python Analysis API, reconstruction from these features on Python Signal and Conversion API, and installation, quick start, and the other API families on the Python API index.
Feature Extraction
from libsonare import Audio
audio = Audio.from_file("music.mp3")
# Spectrogram features
stft_result = audio.stft(n_fft=2048, hop_length=512)
mel = audio.mel_spectrogram(n_fft=2048, hop_length=512, n_mels=128)
mfcc = audio.mfcc(n_fft=2048, hop_length=512, n_mels=128, n_mfcc=20)
chroma = audio.chroma(n_fft=2048, hop_length=512)
# Spectral features
centroid = audio.spectral_centroid()
bandwidth = audio.spectral_bandwidth()
rolloff = audio.spectral_rolloff(roll_percent=0.85)
flatness = audio.spectral_flatness()
zcr = audio.zero_crossing_rate()
rms = audio.rms_energy()
# Pitch detection
pitch_yin = audio.pitch_yin(f0_min_hz=65.0, f0_max_hz=2093.0)
pitch_pyin = audio.pitch_pyin(f0_min_hz=65.0, f0_max_hz=2093.0)
print(f"Median F0: {pitch_pyin.median_f0:.1f} Hz")Feature Extraction Functions
# Compute the short-time Fourier transform.
def stft(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
*,
db: bool = False,
phase: bool = False,
) -> StftResult: ...
# Compute a Mel spectrogram.
def mel_spectrogram(
samples: Sequence[float] | list[float],
sample_rate: int,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
fmin_hz: float = 0.0,
fmax_hz: float | None = None,
htk: bool = False,
) -> MelSpectrogramResult: ...
# Return the mel filterbank as a float32 array of shape ``(n_mels, n_fft // 2 + 1)``.
def mel_filterbank(
sample_rate: int,
n_fft: int,
*,
n_mels: int = 128,
fmin_hz: float = 0.0,
fmax_hz: float | None = None,
htk: bool = False,
norm: MelNorm = 'slaney',
) -> np.ndarray: ...
# Return ``n_mels`` float32 frequencies in Hz equally spaced on the mel scale.
def mel_frequencies(
n_mels: int = 128,
fmin: float = 0.0,
fmax: float = 11025.0,
htk: bool = False,
) -> np.ndarray: ...
# Compute Mel-frequency cepstral coefficients.
def mfcc(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
n_mfcc: int = 20,
fmin: float = 0.0,
fmax: float | None = None,
htk: bool = False,
lifter: float = 0.0,
) -> MfccResult: ...
# Compute STFT chroma features (librosa.feature.chroma_stft).
def chroma(
samples: Sequence[float] | list[float],
sample_rate: int,
n_fft: int = 2048,
hop_length: int = 512,
) -> ChromaResult: ...
# Compute the spectral centroid per frame.
def spectral_centroid(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
) -> np.ndarray: ...
# Compute the spectral bandwidth per frame.
def spectral_bandwidth(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
p: float = 2.0,
) -> np.ndarray: ...
# Compute the spectral rolloff per frame.
def spectral_rolloff(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
roll_percent: float = 0.85,
) -> np.ndarray: ...
# Compute the spectral flatness per frame.
def spectral_flatness(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
) -> np.ndarray: ...
# Compute spectral contrast (librosa.feature.spectral_contrast).
def spectral_contrast(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
n_bands: int = 6,
fmin: float = 200.0,
quantile: float = 0.02,
) -> np.ndarray: ...
# Fit polynomial coefficients per frame (librosa.feature.poly_features).
def poly_features(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
order: int = 1,
) -> np.ndarray: ...
# Compute the zero-crossing rate per frame.
def zero_crossing_rate(
samples: Sequence[float] | list[float],
sr: int = 22050,
frame_length: int = 2048,
hop_length: int = 512,
) -> np.ndarray: ...
# Return zero-crossing sample indices (librosa.zero_crossings).
def zero_crossings(
samples: Sequence[float] | list[float],
threshold: float = 1e-10,
ref_magnitude: bool = False,
pad: bool = True,
zero_pos: bool = True,
) -> np.ndarray: ...
# Compute per-channel min/max waveform buckets from interleaved audio.
def waveform_peaks(
samples: Sequence[float] | list[float],
num_channels: int,
*,
samples_per_bucket: int = 512,
) -> WaveformPeaksReport: ...
# Compute waveform peak buckets for several zoom levels.
def waveform_peak_pyramid(
samples: Sequence[float] | list[float],
num_channels: int,
*,
samples_per_bucket_levels: Sequence[int] = (512, 1024, 2048, 4096),
) -> list[WaveformPeaksReport]: ...
# Compute the RMS energy per frame.
def rms_energy(
samples: Sequence[float] | list[float],
sample_rate: int,
frame_length: int = 2048,
hop_length: int = 512,
) -> np.ndarray: ...
# Estimate fundamental frequency using the YIN algorithm.
def pitch_yin(
samples: Sequence[float] | list[float],
sample_rate: int,
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(
samples: Sequence[float] | list[float],
sample_rate: int,
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: ...
# Per-octave tuning offset from detected pitches (librosa.pitch_tuning).
def pitch_tuning(
frequencies: Sequence[float] | list[float],
resolution: float = 0.01,
bins_per_octave: int = 12,
) -> float: ...
# Global tuning offset of an audio signal (librosa.estimate_tuning).
def estimate_tuning(
samples: Sequence[float] | list[float],
sr: int = 22050,
n_fft: int = 2048,
hop_length: int = 512,
resolution: float = 0.01,
bins_per_octave: int = 12,
) -> float: ...
# Reference frequency of an A4 raised by ``tuning_cents`` cents.
def tuning_to_reference_hz(tuning_cents: float, a4_hz: float = 440.0) -> float: ...
# Tuning, in cents, of a recording whose A4 sits at ``reference_hz``.
def reference_hz_to_tuning(reference_hz: float, a4_hz: float = 440.0) -> float: ...
# Compute the Constant-Q Transform magnitude.
def cqt(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
fmin: float = 32.70319566257483,
n_bins: int = 84,
bins_per_octave: int = 12,
filter_scale: float = 1.0,
) -> CqtResult: ...
# Compute the Variable-Q Transform magnitude (``gamma`` controls Q).
def vqt(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
fmin: float = 32.70319566257483,
n_bins: int = 84,
bins_per_octave: int = 12,
gamma: float | None = None,
filter_scale: float = 1.0,
) -> CqtResult: ...
# Compute the hybrid CQT magnitude; arguments as :func:`cqt`.
def hybrid_cqt(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
fmin: float = 32.70319566257483,
n_bins: int = 84,
bins_per_octave: int = 12,
filter_scale: float = 1.0,
) -> CqtResult: ...
# Compute the pseudo-CQT magnitude approximation; arguments as :func:`cqt`.
def pseudo_cqt(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
fmin: float = 32.70319566257483,
n_bins: int = 84,
bins_per_octave: int = 12,
filter_scale: float = 1.0,
) -> CqtResult: ...
# Compute bass-focused chroma features.
def bass_chroma(
samples: Sequence[float] | list[float],
sample_rate: int,
hop_length: int = 512,
n_chroma: int = 12,
) -> ChromaResult: ...
# Compute CENS chroma features.
def chroma_cens(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
n_chroma: int = 12,
bins_per_octave: int = 36,
) -> ChromaResult: ...
# Compute a constant-Q chromagram (librosa.feature.chroma_cqt).
def chroma_cqt(
samples: Sequence[float] | list[float],
sr: int = 22050,
hop_length: int = 512,
n_chroma: int = 12,
bins_per_octave: int = 36,
) -> ChromaResult: ...
# Compute NNLS chroma.
def nnls_chroma(
samples: Sequence[float] | list[float],
sample_rate: int,
*,
enable_stft_blend: bool = True,
stft_blend_weight: float = 0.55,
stft_blend_n_fft: int = 4096,
hop_length: int = 512,
) -> np.ndarray: ...
# Non-negative matrix factorisation (librosa.decompose.decompose).
def decompose(
s: Sequence[float] | list[float],
n_features: int,
n_frames: int,
n_components: int,
n_iter: int | None = None,
beta: float = 2.0,
init: NmfInit | None = None,
) -> DecomposeResult: ...
# NMF separation that carries the original phase, so components are listenable.
def decompose_stems(
samples: Sequence[float] | list[float],
sample_rate: int,
n_components: int | None = None,
n_fft: int | None = None,
hop_length: int | None = None,
n_iter: int | None = None,
beta: float | None = None,
init: NmfInit | None = None,
mask_power: float | None = None,
) -> DecomposeStemsResult: ...
# N-channel form of :func:`decompose_stems`: one NMF model, one soft mask.
def decompose_stems_linked(
channels: Sequence[Sequence[float] | np.ndarray] | np.ndarray,
sample_rate: int,
n_components: int | None = None,
n_fft: int | None = None,
hop_length: int | None = None,
n_iter: int | None = None,
beta: float | None = None,
init: NmfInit | None = None,
mask_power: float | None = None,
) -> DecomposeStemsLinkedResult: ...
# Nearest-neighbour spectrogram filter (librosa.decompose.nn_filter).
def nn_filter(
s: Sequence[float] | list[float],
n_features: int,
n_frames: int,
aggregate: NnFilterAggregate | None = None,
k: int | None = None,
width: int | None = None,
) -> np.ndarray: ...
# Compute multi-band onset strength as a float32 array of shape ``(n_bands, n_frames)``.
def onset_strength_multi(
samples: Sequence[float] | list[float],
sample_rate: int,
n_fft: int = 2048,
hop_length: int = 512,
n_mels: int = 128,
n_bands: int = 3,
) -> np.ndarray: ...
# Compute the onset strength envelope (librosa.onset.onset_strength).
def onset_strength(
samples: Sequence[float] | list[float],
sr: int = 22050,
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(samples: Sequence[float] | list[float], sample_rate: int) -> LufsResult: ...
# ITU-R BS.1770-4 multi-channel LUFS over an interleaved buffer.
def lufs_interleaved(
samples: Sequence[float] | list[float],
num_channels: int,
sample_rate: int,
) -> LufsResult: ...
# Momentary and short-term LUFS series for an interleaved multi-channel buffer.
def lufs_series_interleaved(
samples: Sequence[float] | list[float],
num_channels: int,
sample_rate: int,
) -> LufsSeriesResult: ...
# EBU R128 / Tech 3342 Loudness Range (LRA) in LU for a mono buffer.
def ebur128_loudness_range_lu(
samples: Sequence[float] | list[float],
sample_rate: int,
) -> float | None: ...
# Compute the per-block momentary LUFS time series as a float32 array.
def momentary_lufs(samples: Sequence[float] | list[float], sample_rate: int) -> np.ndarray: ...
# Compute the per-block short-term LUFS time series as a float32 array.
def short_term_lufs(samples: Sequence[float] | list[float], sample_rate: int) -> np.ndarray: ...| Function | Description |
|---|---|
stft | Short-Time Fourier Transform |
mel_spectrogram | Mel spectrogram; fmin_hz/fmax_hz bound the band edges, htk=True uses the HTK Mel formula. The result carries n_fft, hop_length, fmin_hz, fmax_hz as applied and htk beside the power and db matrices |
mfcc | Mel-Frequency Cepstral Coefficients (lifter=0.0 disables cepstral liftering). The result carries the Mel parameters and lifter it was computed with |
chroma | Chroma features (pitch class distribution) |
spectral_centroid | Spectral centroid per frame |
spectral_bandwidth | Spectral bandwidth per frame |
spectral_rolloff | Spectral rolloff per frame |
spectral_flatness | Spectral flatness per frame |
spectral_contrast | Spectral contrast, shape (n_bands + 1, n_frames) |
poly_features | Per-frame polynomial spectral coefficients |
zero_crossing_rate | Zero-crossing rate per frame |
zero_crossings | Sample indices where the waveform crosses zero |
waveform_peaks | Reduce interleaved multichannel audio (length a multiple of channels) to per-channel min/max buckets for waveform drawing; min/max are channel-major (channel * bucket_count + bucket) |
waveform_peak_pyramid | One peaks report per zoom level (one entry per bucket width) |
rms_energy | RMS energy per frame |
pitch_yin | YIN pitch estimation; every frame has a finite f0, while voiced_flag reports voicing |
pitch_pyin | pYIN pitch estimation; unvoiced f0 stays nan unless fill_na=True |
pitch_tuning | Global tuning offset from detected frequencies, in fractions of a bin |
estimate_tuning | Estimate tuning offset directly from audio, as a fraction of a bin of bins_per_octave (the analysis unit at 12) |
tuning_to_reference_hz / reference_hz_to_tuning | Convert between the tuning offset in cents and a reference pitch in Hz |
cqt | Constant-Q Transform magnitude |
vqt | Variable-Q Transform magnitude; gamma=None selects the automatic bandwidth, 0.0 is equivalent to CQT |
hybrid_cqt | Hybrid CQT magnitude (CQT/pseudo-CQT blend across bins) |
pseudo_cqt | Approximate (pseudo) CQT magnitude |
bass_chroma | Bass-focused chroma (low-register pitch-class distribution) |
chroma_cens | CENS energy-normalized/smoothed chroma |
chroma_cqt | Constant-Q chromagram (librosa.feature.chroma_cqt equivalent) — features has shape (n_chroma, n_frames) |
nnls_chroma | NNLS chromagram of shape (12, n_frames); hop_length defaults to 512 |
decompose | NMF decomposition factors (w, h) from a row-major spectrogram |
decompose_stems | NMF separation that masks the original complex spectrogram, so the components keep the source's phase and sum back to the input; defaults n_components=4, n_iter=100, beta=2.0, init='random', mask_power=1.0 |
decompose_stems_linked | Shared NMF separation for one or more same-length channels (maximum 64); preserves interchannel level and phase, and returns components[k][c] planes. Defaults match decompose_stems; one channel is bit-identical |
nn_filter | Nearest-neighbor filtering of a row-major spectrogram |
onset_strength_multi | Multi-band onset strength of shape (n_bands, n_frames) (n_bands default 3) |
onset_strength | Onset strength envelope (half-wave rectified Mel-spectrogram flux), one float32 value per frame |
lufs | Integrated/final-window LUFS (Loudness Units relative to Full Scale), Max-M / Max-S, and loudness range (EBU R128) |
lufs_interleaved | Channel-weighted multichannel loudness from interleaved samples |
lufs_series_interleaved | Momentary and short-term LUFS series for interleaved multichannel samples, summed across channels as BS.1770-4 specifies |
ebur128_loudness_range_lu | EBU R128 loudness range (LRA) in LU |
momentary_lufs | Momentary LUFS per frame |
short_term_lufs | Short-term LUFS per frame |
Common defaults: n_fft=2048, hop_length=512, n_mels=128, n_mfcc=20, pitch fmin=65.0, fmax=2093.0, threshold=0.1, and roll_percent=0.85.
CQT/VQT use fmin=32.70319566 Hz (C1), n_bins=84, and bins_per_octave=12. VQT's default gamma=None selects automatic ERB-derived bandwidth; a negative or non-finite gamma, NaN included, is refused. chroma_cqt and chroma_cens default to n_chroma=12 and bins_per_octave=36. hpss(...) defaults to kernel_harmonic=31, kernel_percussive=31, n_fft=2048, hop_length=None (a quarter of n_fft, 512) and hard_mask=False.
Additional effect helpers include phase_vocoder and hpss(..., with_residual=True). Use them when you need direct phase-vocoder time scaling (speed_ratio above 1 is faster and shorter), or HPSS with the residual signal preserved in HpssResult.residual.
# Phase-vocoder time-scale modification (STFT -> phase_vocoder -> iSTFT).
def phase_vocoder(
samples: Sequence[float] | list[float],
sample_rate: int,
speed_ratio: float,
n_fft: int = 2048,
hop_length: int | None = None,
) -> np.ndarray: ...NMF factors versus listenable stems
decompose returns the W / H factors of a magnitude spectrogram. Those factors carry no phase, so reconstructing audio from them needs a phase estimator, and an estimated phase does not hold up as a stem. decompose_stems builds a per-component soft mask from the same factorisation and applies it to the original complex spectrogram instead, so every component keeps the source's phase. The masks sum to one wherever the model has energy and the inverse STFT is linear, so the components sum back to the input.
mask_power is the soft-mask exponent: 1 (the default) keeps the magnitude ratio, 2 is the Wiener-style power ratio, which separates harder at the cost of more artifacts on overlapping partials. Values below 1 are refused. init is 'random' by default, or 'nndsvd' for the SVD warm start; beta is the divergence (2 = Frobenius, 1 = Kullback-Leibler).
stems = sonare.decompose_stems(audio.data, audio.sample_rate, n_components=4, mask_power=2.0)
for component in stems.components:
... # each is a 1-D float32 array the length of the input
print(stems.w.shape, stems.h.shape, stems.sample_rate)For multichannel input, use decompose_stems_linked(...). It fits one NMF model and one soft-mask set from the channels' averaged magnitudes, then applies each mask unchanged to each channel's original complex spectrum. This preserves interchannel level and phase. Pass one or more same-length channels, with no more than 64 channels. Each components[k] is a two-dimensional float32 array whose rows are channels, so components[k][c] is component k on channel c. The w and h arrays are shared across channels, and all defaults match decompose_stems; one channel is bit-identical to decompose_stems(...).
linked = sonare.decompose_stems_linked(
[left_channel, right_channel], sample_rate=sample_rate
)
first_left = linked.components[0][0]
first_right = linked.components[0][1]
print(linked.w.shape, linked.h.shape)Omit n_components, n_fft, hop_length or n_iter to use the defaults. An omitted hop length is derived from n_fft. An explicit zero is refused in Python and JavaScript.
NNDSVD seeding is solved in double precision
This makes the factors reproducible, not more accurate. A magnitude spectrogram's trailing singular vectors sit at single precision's noise floor, so a float seed would depend on summation order and different targets would answer with different components. Shapes, non-negativity and reconstruction quality are unaffected. decompose and decompose_stems return different factors from a single-precision seed for the same input, so stored factors, or a stem render made with one, will not match.