Features, Tonal, Constant-Q and Pitch Analysis

Frame-wise spectral features, chroma and tuning estimation, the constant-Q family (cqt, vqt, icqt, chroma and tonnetz) and the YIN / pYIN pitch trackers.

Entry points:

  • methods on audio_samples.AudioSamples, which take the sample rate from the audio and always return (channels, n_features, n_frames) arrays (pitch trackers: (channels, n_frames)); index [0] for mono audio;

  • audio_samples.features: array functions that take a spectrogram S, a constant-Q transform C or a chromagram, plus the filterbanks and helpers behind them; a 2-D input gives 2-D output and a 3-D (channels, ...) input 3-D output;

  • audio_samples.utils: tuning, octave and key conversions.

Output follows the input’s precision: float32 / complex64 for uint8, int16, int24 and float32 audio (or float32 arrays), float64 / complex128 otherwise. Filterbanks, wavelets and frequency weightings are float64 tables. res_type selects this library’s resampler quality for the constant-Q octave decimation. Only intervals="equal" (VQT) and kind="linear" (harmonics) are supported, and time is the last axis.

AudioSamples methods

Frame-wise features

AudioSamples.spectral_centroid_frames(*, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='constant')

Spectral centroid of every frame: the magnitude-weighted mean frequency.

Computed from the magnitude STFT. For several descriptors of one spectrogram use features.spectral_centroid_from_spectrogram.

Parameters:
  • n_fft (int) – FFT length. Default 2048.

  • hop_length (int) – Samples between frames. Default 512.

  • win_length (Optional[int]) – Window length; None = n_fft.

  • window – Window specification (see stft_matrix). Default "hann".

  • center (bool) – Centre frames. Default True.

  • pad_mode (str) – Padding for center. Default "constant".

Returns:

shape (channels, 1, n_frames) in Hz, also for mono audio (index [0] for (1, n_frames)).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters or a too-short uncentred signal.

AudioSamples.spectral_bandwidth_frames(*, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='constant', norm=True, p=2.0)

Order-p spectral bandwidth of every frame around the spectral centroid.

Parameters:
  • n_fft (default 512) – As spectral_centroid_frames.

  • hop_length (default 512) – As spectral_centroid_frames.

  • norm (bool) – Normalise each frame to unit sum. Default True.

  • p (float) – Order of the deviation. Default 2.

Returns:

shape (channels, 1, n_frames) in Hz.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

AudioSamples.spectral_rolloff_frames(*, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='constant', roll_percent=0.85)

Roll-off frequency of every frame: the frequency below which roll_percent of the energy lies.

Parameters:
  • n_fft (default 512) – As spectral_centroid_frames.

  • hop_length (default 512) – As spectral_centroid_frames.

  • roll_percent (float) – Energy fraction in (0, 1). Default 0.85.

Returns:

shape (channels, 1, n_frames) in Hz.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

AudioSamples.spectral_flatness_frames(*, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='constant', amin=1e-10, power=2.0)

Spectral flatness of every frame: the geometric over the arithmetic mean of the power spectrum.

Parameters:
  • n_fft (default 512) – As spectral_centroid_frames.

  • hop_length (default 512) – As spectral_centroid_frames.

  • amin (float) – Floor of |S| ** power. Default 1e-10.

  • power (float) – Exponent of the magnitude. Default 2.0.

Returns:

shape (channels, 1, n_frames), in [0, 1].

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

AudioSamples.spectral_contrast_frames(*, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='constant', fmin=200.0, n_bands=6, quantile=0.02, linear=False)

Octave-band spectral contrast of every frame: the peak-to-valley difference in each band, in dB.

Parameters:
  • n_fft (default 512) – As spectral_centroid_frames.

  • hop_length (default 512) – As spectral_centroid_frames.

  • fmin (float) – Upper edge of the lowest band (Hz). Default 200.

  • n_bands (int) – Number of octave bands. Default 6.

  • quantile (float) – Fraction used for peak / valley. Default 0.02.

  • linear (bool) – Linear difference instead of dB. Default False.

Returns:

shape (channels, n_bands + 1, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters (e.g. the top band above Nyquist).

AudioSamples.poly_features(*, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='constant', order=1)

Coefficients of a least-squares polynomial fit to every magnitude-spectrum frame against the bin frequencies.

Parameters:
  • n_fft (default 512) – As spectral_centroid_frames.

  • hop_length (default 512) – As spectral_centroid_frames.

  • order (int) – Polynomial order. Default 1.

Returns:

shape (channels, order + 1, n_frames), highest power first.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

AudioSamples.rms_frames(*, frame_length=2048, hop_length=512, center=True, pad_mode='constant')

Frame-wise root-mean-square energy.

Unlike the scalar rms(), this returns one value per frame.

Parameters:
  • frame_length (int) – Samples per frame. Default 2048.

  • hop_length (int) – Samples between frames. Default 512.

  • center (bool) – Centre frames (pad frame_length // 2). Default True.

  • pad_mode (str) – Padding for center. Default "constant".

Returns:

shape (channels, 1, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters or a too-short uncentred signal.

AudioSamples.zero_crossing_rate_frames(*, frame_length=2048, hop_length=512, center=True, threshold=1e-10, ref_magnitude=None, pad=False, zero_pos=True)

Frame-wise zero-crossing rate (fraction of sign changes per frame).

Unlike the scalar zero_crossing_rate() (crossings per second), this returns one fraction per frame. Centring always uses edge padding.

Parameters:
  • frame_length (int) – Samples per frame. Default 2048.

  • hop_length (int) – Samples between frames. Default 512.

  • center (bool) – Centre frames. Default True.

  • threshold (float) – |x| <= threshold * ref counts as zero. Default 1e-10.

  • ref_magnitude (None | float | numpy.max) – Threshold scale. Default None.

  • pad (bool) – Count the first sample of every frame as a crossing. Default False.

  • zero_pos (bool) – Zero counts as positive. Default True.

Returns:

shape (channels, 1, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

AudioSamples.reassigned_spectrogram(*, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, reassign_frequencies=True, reassign_times=True, ref_power=1e-06, fill_nan=False, clip=True, pad_mode='constant')

Time-frequency reassigned spectrogram: the instantaneous frequency and group-delay time of every bin.

Parameters:
  • n_fft (int) – FFT length. Default 2048.

  • hop_length (Optional[int]) – None = win_length // 4.

  • win_length (Optional[int]) – None = n_fft.

  • window – Window specification. Default "hann".

  • center (bool) – Centre frames. Default True.

  • reassign_frequencies (bool) – Reassign frequencies. Default True.

  • reassign_times (bool) – Reassign times. Default True.

  • ref_power (float | numpy.max) – Power threshold below which estimates are NaN. Default 1e-6.

  • fill_nan (bool) – Replace NaN estimates by bin / frame centres. Default False.

  • clip (bool) – Clip to [0, sr / 2] and [0, duration]. Default True.

  • pad_mode (str) – Padding for center. Default "constant".

Returns:

(freqs, times, mags), each numpy.ndarray[float32 | float64] of shape (channels, 1 + n_fft // 2, n_frames).

Return type:

tuple

Raises:

ValueError – For invalid parameters.

Tonal

AudioSamples.chroma_stft(*, norm=inf, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='constant', tuning=0.0, n_chroma=12, ctroct=5.0, octwidth=2.0, base_c=True)

Chromagram from the power STFT.

chroma() (spectrograms crate) is a separate implementation; this one uses the chroma_filterbank with optional tuning estimation and per-frame norm normalisation.

Parameters:
  • norm (Optional[float]) – Per-frame normalisation (numpy.inf default, any p-norm, or None for raw energy).

  • n_fft (int) – FFT length. Default 2048.

  • hop_length (int) – Samples between frames. Default 512.

  • win_length – STFT parameters (see stft_matrix).

  • window – STFT parameters (see stft_matrix).

  • center – STFT parameters (see stft_matrix).

  • pad_mode – STFT parameters (see stft_matrix).

  • tuning (Optional[float]) – Tuning offset in fractions of a chroma bin. Default 0.0; None estimates it from the signal.

  • n_chroma (int) – Number of chroma bins. Default 12.

  • ctroct (float) – Centre of the octave weighting (octaves above A0). Default 5.

  • octwidth (Optional[float]) – Octave-weighting half-width; None = flat. Default 2.

  • base_c (bool) – Row 0 is C (True) or A. Default True.

Returns:

shape (channels, n_chroma, n_frames), also for mono audio (index [0] for (n_chroma, n_frames)).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

AudioSamples.piptrack(*, n_fft=2048, hop_length=None, fmin=150.0, fmax=4000.0, threshold=0.1, win_length=None, window='hann', center=True, pad_mode='constant', ref=None)

Spectral peak tracking with parabolic interpolation.

Parameters:
  • n_fft (int) – FFT length. Default 2048.

  • hop_length (Optional[int]) – None = win_length // 4.

  • fmin (float) – Lowest reported frequency (Hz). Default 150.

  • fmax (float) – Peaks must lie below this frequency (Hz). Default 4000.

  • threshold (float) – Relative threshold. Default 0.1.

  • win_length – STFT parameters.

  • window – STFT parameters.

  • center – STFT parameters.

  • pad_mode – STFT parameters.

  • ref (None | float | numpy.max | numpy.mean) – Threshold reference; None (default) = per-frame maximum, a number = absolute threshold.

Returns:

(pitches, magnitudes), each numpy.ndarray[float32 | float64] of shape (channels, 1 + n_fft // 2, n_frames); zero except at detected peaks.

Return type:

tuple

Raises:

ValueError – For invalid parameters.

AudioSamples.estimate_tuning(*, n_fft=2048, resolution=0.01, bins_per_octave=12, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant', fmin=150.0, fmax=4000.0, threshold=0.1, ref=None)

Tuning offset relative to A440 in fractions of a bin, estimated from spectral peaks.

All channels are pooled.

Parameters:
  • n_fft (int) – FFT length. Default 2048.

  • resolution (float) – Resolution in fractions of a bin. Default 0.01.

  • bins_per_octave (int) – Bins per octave of the grid. Default 12.

  • hop_length – piptrack parameters.

  • win_length – piptrack parameters.

  • window – piptrack parameters.

  • center – piptrack parameters.

  • pad_mode – piptrack parameters.

  • fmin – piptrack parameters.

  • fmax – piptrack parameters.

  • threshold – piptrack parameters.

  • ref – piptrack parameters.

Returns:

tuning in [-0.5, 0.5) fractions of a bin.

Return type:

float

Raises:

ValueError – For invalid parameters.

Constant-Q

AudioSamples.cqt(*, hop_length=512, fmin=None, n_bins=84, bins_per_octave=12, tuning=0.0, filter_scale=1, norm=1, sparsity=0.01, window='hann', scale=True, pad_mode='constant', res_type='soxr_hq')

Constant-Q transform of every channel.

constant_q_transform() (spectrograms crate) is a separate implementation with its own filters, scaling and framing.

Parameters:
  • hop_length (int) – Samples between frames. Default 512.

  • fmin (Optional[float]) – Lowest bin frequency (Hz); None = C1 (32.70 Hz).

  • n_bins (Optional[int]) – Number of bins (default 84); None = as many as fit below Nyquist.

  • bins_per_octave (int) – Default 12.

  • tuning (Optional[float]) – Tuning offset in fractions of a bin (default 0.0); None estimates it from the signal.

  • filter_scale (float) – Filter-length scale. Default 1.

  • norm (Optional[float]) – Filter normalisation (p-norm). Default 1.

  • sparsity (float) – Fraction of each filter’s mass that may be dropped. Default 0.01.

  • window – Named window of the filters. Default "hann".

  • scale (bool) – Divide by sqrt(filter length). Default True.

  • pad_mode (str) – Padding at the signal ends. Default "constant".

  • res_type (str) – Quality of the crate’s resampler for the octave decimation: "soxr_hq" (default) high, "soxr_vhq" very high, "soxr_mq" medium, "soxr_lq" fast.

Returns:

shape (channels, n_bins, n_frames), also for mono audio (index [0] for (n_bins, n_frames)).

Return type:

numpy.ndarray[complex64 | complex128]

Raises:

ValueError – For invalid parameters (e.g. bins above Nyquist).

AudioSamples.vqt(*, hop_length=512, fmin=None, n_bins=84, intervals='equal', gamma=None, bins_per_octave=12, tuning=0.0, filter_scale=1, norm=1, sparsity=0.01, window='hann', scale=True, pad_mode='constant', res_type='soxr_hq')

Variable-Q transform of every channel.

Parameters:
  • hop_length – As cqt.

  • fmin – As cqt.

  • n_bins – As cqt.

  • bins_per_octave – As cqt.

  • tuning – As cqt.

  • filter_scale – As cqt.

  • norm – As cqt.

  • sparsity – As cqt.

  • window – As cqt.

  • scale – As cqt.

  • pad_mode – As cqt.

  • res_type – As cqt.

  • intervals (str) – Only "equal" (equal temperament) is supported.

  • gamma (Optional[float]) – Bandwidth offset (Hz); None (default) = ERB-derived, 0 = constant-Q.

Returns:

shape (channels, n_bins, n_frames).

Return type:

numpy.ndarray[complex64 | complex128]

Raises:

ValueError – For invalid parameters or intervals other than "equal".

AudioSamples.pseudo_cqt(*, hop_length=512, fmin=None, n_bins=84, bins_per_octave=12, tuning=0.0, filter_scale=1, norm=1, sparsity=0.01, window='hann', scale=True, pad_mode='constant')

Pseudo constant-Q magnitude: constant-Q filters applied to a single STFT.

Parameters:
  • hop_length – As cqt.

  • fmin – As cqt.

  • n_bins – As cqt.

  • bins_per_octave – As cqt.

  • tuning – As cqt.

  • filter_scale – As cqt.

  • norm – As cqt.

  • sparsity – As cqt.

  • window – As cqt.

  • scale – As cqt.

  • pad_mode – As cqt.

Returns:

magnitudes, shape (channels, n_bins, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

AudioSamples.hybrid_cqt(*, hop_length=512, fmin=None, n_bins=84, bins_per_octave=12, tuning=0.0, filter_scale=1, norm=1, sparsity=0.01, window='hann', scale=True, pad_mode='constant', res_type='soxr_hq')

Hybrid constant-Q magnitude: pseudo-CQT for the high bins, full CQT for the low bins.

Parameters:

cqt. (As)

Returns:

magnitudes, shape (channels, n_bins, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

static AudioSamples.icqt(C, *, sample_rate, hop_length=512, fmin=None, bins_per_octave=12, tuning=0.0, filter_scale=1, norm=1, sparsity=0.01, window='hann', scale=True, length=None, res_type='soxr_hq', dtype=None)

Inverse constant-Q transform.

This is a static method: AudioSamples.icqt(C, sample_rate=sr).

Parameters:
  • C (array_like) – complex CQT of shape (n_bins, T) or (channels, n_bins, T).

  • sample_rate (int) – Sample rate of the analysed signal (keyword-only).

  • hop_length – The forward parameters (see cqt).

  • fmin – The forward parameters (see cqt).

  • bins_per_octave – The forward parameters (see cqt).

  • filter_scale – The forward parameters (see cqt).

  • norm – The forward parameters (see cqt).

  • sparsity – The forward parameters (see cqt).

  • window – The forward parameters (see cqt).

  • scale – The forward parameters (see cqt).

  • res_type – The forward parameters (see cqt).

  • tuning (float) – Tuning used by the forward transform. Default 0.0.

  • length (Optional[int]) – Exact output length per channel.

  • dtype (Optional[SampleType]) – Sample type of the returned audio. None (default) gives float32 audio for a complex64 C and float64 audio for any other input. The computation runs in the float type of dtype (float32 for U8, I16, I24 and F32; float64 for I32 and F64); integer output is rounded and saturated.

Returns:

audio of sample type dtype (mono for a single channel).

Return type:

AudioSamples

Raises:

ValueError – For invalid parameters or an empty C.

static AudioSamples.griffinlim_cqt(C, *, sample_rate, n_iter=32, hop_length=512, fmin=None, bins_per_octave=12, tuning=0.0, filter_scale=1, norm=1, sparsity=0.01, window='hann', scale=True, pad_mode='constant', res_type='soxr_hq', length=None, momentum=0.99, init=None, rng=0, random_state=None, dtype=None)

Reconstructs audio from a constant-Q magnitude by Griffin-Lim.

This is a static method. The default is the deterministic zero-phase start (init=None).

Parameters:
  • C (array_like) – Non-negative CQT magnitude, (n_bins, T) or (channels, n_bins, T).

  • sample_rate (int) – Sample rate (keyword-only).

  • n_iter (int) – Iterations. Default 32.

  • hop_length – The forward parameters (see cqt).

  • fmin – The forward parameters (see cqt).

  • bins_per_octave – The forward parameters (see cqt).

  • tuning – The forward parameters (see cqt).

  • filter_scale – The forward parameters (see cqt).

  • norm – The forward parameters (see cqt).

  • sparsity – The forward parameters (see cqt).

  • window – The forward parameters (see cqt).

  • scale – The forward parameters (see cqt).

  • pad_mode – The forward parameters (see cqt).

  • res_type – The forward parameters (see cqt).

  • length (Optional[int]) – Output length per channel.

  • momentum (float) – Fast Griffin-Lim momentum. Default 0.99.

  • init (Optional[str]) – None (default: zero phase, deterministic) or "random".

  • rng – Seed for init="random", as griffinlim: an integer (default 0), None for a fresh seed on every call, or a NumPy generator, from which one seed is drawn. The random phases come from this library’s generator.

  • random_state – Deprecated alias of rng.

  • dtype (Optional[SampleType]) – Sample type of the returned audio. None (default) gives float32 audio for a float32 C and float64 audio for any other input. The computation runs in the float type of dtype (float32 for U8, I16, I24 and F32; float64 for I32 and F64); integer output is rounded and saturated.

Returns:

audio of sample type dtype.

Return type:

AudioSamples

Raises:

ValueError – For invalid parameters or init other than None or "random".

AudioSamples.chroma_cqt(*, hop_length=512, fmin=None, norm=inf, threshold=0.0, tuning=0.0, n_chroma=12, n_octaves=7, window=None, bins_per_octave=36, cqt_mode='full')

Constant-Q chromagram.

Parameters:
  • hop_length (int) – Default 512.

  • fmin (Optional[float]) – Lowest CQT frequency; None = C1.

  • norm (Optional[float]) – Per-frame normalisation. Default numpy.inf.

  • threshold (Optional[float]) – Values below are zeroed. Default 0.0.

  • tuning (Optional[float]) – Tuning in fractions of a CQT bin. Default 0.0; None estimates it from the signal.

  • n_chroma (int) – Default 12.

  • n_octaves (int) – Default 7.

  • window – Must be None (a chroma smoothing window is not supported).

  • bins_per_octave (Optional[int]) – CQT resolution (multiple of n_chroma). Default 36; None = n_chroma.

  • cqt_mode (str) – "full" (default) or "hybrid".

Returns:

shape (channels, n_chroma, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

AudioSamples.chroma_cens(*, hop_length=512, fmin=None, tuning=0.0, n_chroma=12, n_octaves=7, bins_per_octave=36, cqt_mode='full', window=None, norm=2, win_len_smooth=41, smoothing_window='hann')

Chroma Energy Normalized Statistics (CENS) features.

Parameters:
  • hop_length – As chroma_cqt.

  • fmin – As chroma_cqt.

  • tuning – As chroma_cqt.

  • n_chroma – As chroma_cqt.

  • n_octaves – As chroma_cqt.

  • bins_per_octave – As chroma_cqt.

  • cqt_mode – As chroma_cqt.

  • window – As chroma_cqt.

  • norm (Optional[float]) – Final per-frame normalisation. Default 2.

  • win_len_smooth (Optional[int]) – Smoothing length in frames (None disables). Default 41.

  • smoothing_window – Smoothing window shape. Default "hann".

Returns:

shape (channels, n_chroma, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

AudioSamples.chroma_vqt(*, hop_length=512, fmin=None, intervals='equal', norm=inf, threshold=0.0, n_octaves=7, bins_per_octave=12, gamma=0)

Variable-Q chromagram with equal-tempered bin spacing.

Parameters:
  • hop_length (int) – Default 512.

  • fmin (Optional[float]) – Lowest VQT frequency; None = C1.

  • intervals (str) – Only "equal" (the default).

  • norm (Optional[float]) – Per-frame normalisation. Default numpy.inf.

  • threshold (Optional[float]) – Values below are zeroed. Default 0.0.

  • n_octaves (int) – Default 7.

  • bins_per_octave (int) – VQT bins per octave (= chroma bins). Default 12.

  • gamma (Optional[float]) – Bandwidth offset (Hz); 0 (default) = CQT, None = ERB-derived.

Returns:

shape (channels, bins_per_octave, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters or intervals other than "equal".

AudioSamples.tonnetz(*, hop_length=512, fmin=None, norm=inf, threshold=0.0, tuning=0.0, n_chroma=12, n_octaves=7, bins_per_octave=36, cqt_mode='full')

Tonal centroid features (tonnetz) from the constant-Q chroma.

Parameters:
  • hop_length – chroma_cqt parameters.

  • fmin – chroma_cqt parameters.

  • norm – chroma_cqt parameters.

  • threshold – chroma_cqt parameters.

  • tuning – chroma_cqt parameters.

  • n_chroma – chroma_cqt parameters.

  • n_octaves – chroma_cqt parameters.

  • bins_per_octave – chroma_cqt parameters.

  • cqt_mode – chroma_cqt parameters.

Returns:

shape (channels, 6, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

Pitch tracking

AudioSamples.yin(*, fmin, fmax, frame_length=2048, hop_length=None, trough_threshold=0.1, center=True, pad_mode='constant')

Frame-wise YIN fundamental frequency.

Unlike detect_pitch_yin() / track_pitch(), this uses centred frames, the cumulative mean normalised difference (CMND), parabolic refinement of the chosen trough and a fallback to the global minimum when no trough is below trough_threshold.

Parameters:
  • fmin (float) – Lowest frequency searched (Hz). Required (e.g. C2 = 65.41).

  • fmax (float) – Highest frequency searched (Hz). Required (e.g. C7 = 2093.0).

  • frame_length (int) – Samples per frame. Default 2048.

  • hop_length (Optional[int]) – None = frame_length // 4.

  • trough_threshold (float) – Absolute CMND threshold. Default 0.1.

  • center (bool) – Centre frames on t * hop_length. Default True.

  • pad_mode (str) – Padding for center. Default "constant".

Returns:

f0 in Hz, shape (channels, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters (e.g. fmax > sr / 2) or a too-short uncentred signal.

AudioSamples.pyin(*, fmin, fmax, frame_length=2048, hop_length=None, n_thresholds=100, beta_parameters=(2, 18), boltzmann_parameter=2, resolution=0.1, max_transition_rate=35.92, switch_prob=0.01, no_trough_prob=0.01, fill_na=nan, center=True, pad_mode='constant', transition_min_prob=0.0001)

Probabilistic YIN with HMM decoding: f0 tracking with voicing decisions.

Parameters:
  • fmin (float) – Search range in Hz. Required.

  • fmax (float) – Search range in Hz. Required.

  • frame_length (int) – Default 2048.

  • hop_length (Optional[int]) – None = frame_length // 4.

  • n_thresholds (int) – Default 100.

  • beta_parameters (tuple[float, float]) – Beta prior. Default (2, 18).

  • boltzmann_parameter (float) – Default 2.

  • resolution (float) – Pitch-bin width in semitones. Default 0.1.

  • max_transition_rate (float) – Octaves per second. Default 35.92.

  • switch_prob (float) – Voiced/unvoiced switch probability. Default 0.01.

  • no_trough_prob (float) – Default 0.01.

  • fill_na (Optional[float]) – f0 of unvoiced frames: NaN (default), None (the best-guess pitch) or a number.

  • center (bool) – Default True.

  • pad_mode (str) – Default "constant".

  • transition_min_prob (Optional[float]) – Viterbi pruning threshold (None or 0 = exact decoding). Default 1e-4.

Returns:

(f0, voiced_flag, voiced_prob), each of shape (channels, n_frames): Hz, bool, values in [0, 1]; the float arrays are float32 for uint8, int16, int24 and float32 audio and float64 otherwise.

Return type:

tuple

Raises:

ValueError – For invalid parameters or a too-short uncentred signal.

Array functions (audio_samples.features)

Feature, tonal, constant-Q and pitch functions over NumPy arrays: spectral descriptors of a spectrogram, pcen, frequency weightings, chroma filterbanks and tuning (chroma_filterbank, pitch_tuning, estimate_tuning_from_spectrogram, normalize), constant-Q filters (cq_to_chroma, wavelet), chroma_cens / tonnetz from a chromagram, yin / pyin on arrays and the harmonic helpers (salience, interp_harmonics, f0_harmonics). float32 / complex64 arrays are processed in float32 and give float32 output; any other input is converted to float64.

Spectral descriptors

audio_samples.features.spectral_centroid_from_spectrogram(S, *, sr, freq=None)

Spectral centroid of every frame of a spectrogram: the magnitude-weighted mean frequency.

Parameters:
  • S (array_like) – Non-negative magnitude spectrogram, shape (F, T) or (channels, F, T).

  • sr (float) – Sample rate (Hz), used for the default freq. Required.

  • freq (Optional[array_like]) – Centre frequency of each bin (Hz): 1-D, or time-varying with the shape of S ((F, T) is shared by all channels). None uses fft_frequencies(sr, n_fft=2 * (F - 1)).

Returns:

shape (1, T) or (channels, 1, T), in Hz.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – If S has negative or non-finite values, or freq has the wrong shape.

audio_samples.features.spectral_bandwidth_from_spectrogram(S, *, sr, freq=None, centroid=None, norm=True, p=2.0)

Order-p spectral bandwidth of every frame around the spectral centroid.

Parameters:
  • S (array_like) – Non-negative spectrogram, (F, T) or (channels, F, T).

  • sr (float) – Sample rate for the default freq. Required.

  • freq (Optional[array_like]) – Bin frequencies, 1-D or time-varying with the shape of S; None = FFT bin centres.

  • centroid (Optional[array_like]) – Precomputed centroid, shape (1, T) or (channels, 1, T); None computes it.

  • norm (bool) – Normalise each frame to unit sum first. Default True.

  • p (float) – Order of the deviation. Default 2.

Returns:

shape (1, T) or (channels, 1, T), in Hz.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid spectrogram values or shapes, or p zero / not finite.

audio_samples.features.spectral_rolloff_from_spectrogram(S, *, sr, freq=None, roll_percent=0.85)

Roll-off frequency of every frame: the frequency below which roll_percent of the energy lies.

Parameters:
  • S (array_like) – Non-negative spectrogram, (F, T) or (channels, F, T).

  • sr (float) – Sample rate for the default freq. Required.

  • freq (Optional[array_like]) – Bin frequencies, 1-D or time-varying with the shape of S; None = FFT bin centres.

  • roll_percent (float) – Energy fraction in (0, 1). Default 0.85.

Returns:

shape (1, T) or (channels, 1, T), in Hz.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid spectrogram values or roll_percent outside (0, 1).

audio_samples.features.spectral_flatness_from_spectrogram(S, *, amin=1e-10, power=2.0)

Spectral flatness (Wiener entropy) of every frame: the geometric over the arithmetic mean of S ** power.

Parameters:
  • S (array_like) – Non-negative magnitude spectrogram, (F, T) or (channels, F, T).

  • amin (float) – Floor applied to S ** power. Default 1e-10.

  • power (float) – Exponent applied to S. Default 2.0.

Returns:

shape (1, T) or (channels, 1, T), in [0, 1].

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid spectrogram values, amin <= 0 or power <= 0.

audio_samples.features.spectral_contrast_from_spectrogram(S, *, sr, freq=None, fmin=200.0, n_bands=6, quantile=0.02, linear=False)

Octave-band spectral contrast of every frame: the peak-to-valley difference in each band, in dB.

Parameters:
  • S (array_like) – Non-negative magnitude spectrogram, (F, T) or (channels, F, T).

  • sr (float) – Sample rate (Hz). Required.

  • freq (Optional[array_like]) – 1-D bin frequencies; None = FFT bin centres.

  • fmin (float) – Upper edge of the lowest band (Hz). Default 200.

  • n_bands (int) – Number of octave bands above fmin. Default 6.

  • quantile (float) – Fraction of each band used for peak / valley. Default 0.02.

  • linear (bool) – Linear difference instead of a dB ratio. Default False.

Returns:

shape (n_bands + 1, T) or (channels, n_bands + 1, T).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters (e.g. the top band above Nyquist).

audio_samples.features.poly_features_from_spectrogram(S, *, sr, freq=None, order=1)

Coefficients of a least-squares polynomial fit of every frame against the bin frequencies.

Parameters:
  • S (array_like) – Spectrogram, (F, T) or (channels, F, T).

  • sr (float) – Sample rate for the default freq. Required.

  • freq (Optional[array_like]) – 1-D bin frequencies; None = FFT bin centres.

  • order (int) – Polynomial order. Default 1.

Returns:

shape (order + 1, T) or (channels, order + 1, T), highest power first (as numpy.polyfit).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – If order is negative or not below the number of bins.

audio_samples.features.rms_from_spectrogram(S, *, frame_length=2048)

Frame-wise RMS from STFT magnitudes (Parseval).

Parameters:
  • S (array_like) – STFT magnitudes, (1 + frame_length // 2, T) or (channels, 1 + frame_length // 2, T).

  • frame_length (int) – The FFT length used to compute S. Default 2048.

Returns:

shape (1, T) or (channels, 1, T).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – If the bin count is not 1 + frame_length // 2.

audio_samples.features.pcen(S, *, sr, hop_length, gain=0.98, bias=2.0, power=0.5, time_constant=0.4, eps=1e-06, b=None, max_size=1, ref=None, axis=-1, max_axis=None, zi=None, return_zf=False)

Per-channel energy normalisation (PCEN) of a spectrogram.

Time is the last axis (axis=-1) and the max filter runs along frequency, the axis before it (max_axis=-2).

Parameters:
  • S (array_like) – Non-negative spectrogram, (F, T) or (channels, F, T) (typically a mel power spectrogram scaled to integer range).

  • sr (float) – Sample rate (Hz). Required.

  • hop_length (int) – Hop of S in samples. Required.

  • gain (float) – Gain-normalisation exponent. Default 0.98.

  • bias (float) – Bias added before compression. Default 2.

  • power (float) – Compression exponent (0 selects log1p). Default 0.5.

  • time_constant (float) – Smoothing time constant (s). Default 0.4.

  • eps (float) – Floor of the smoother. Default 1e-6.

  • b (Optional[float]) – Explicit smoothing coefficient in [0, 1].

  • max_size (int) – Width of a maximum filter along frequency applied to S before smoothing. Default 1 (off).

  • ref (Optional[array_like]) – Array (shape of S) to smooth instead of S.

  • axis (int) – Must be -1 (or S.ndim - 1).

  • max_axis (Optional[int]) – Must be None or the frequency axis (-2).

  • zi (Optional[array_like]) – Initial filter state, shape (..., F, 1) (e.g. a previous zf); None = steady state for a unit input.

  • return_zf (bool) – Also return the final filter state. Default False.

Returns:

the PCEN spectrogram (shape of S), and with return_zf=True also zf of shape (..., F, 1).

Return type:

numpy.ndarray[float32 | float64] | tuple

Raises:

ValueError – For invalid parameters, unsupported axis / max_axis or shape mismatches. Complex S raises TypeError (pass numpy.abs(S)).

Frequency weighting

audio_samples.features.a_weighting(frequencies, *, min_db=-80.0)

The A-weighting of a set of frequencies in dB.

Parameters:
  • frequencies (float | array_like) – Frequencies in Hz.

  • min_db (Optional[float]) – Lower clip in dB (default -80); None disables it.

Returns:

dB weights, same shape as frequencies (a float for scalar input).

Return type:

float | numpy.ndarray[float64]

audio_samples.features.b_weighting(frequencies, *, min_db=-80.0)

The B-weighting of a set of frequencies in dB.

Parameters:
  • frequencies (float | array_like) – Frequencies in Hz.

  • min_db (Optional[float]) – Lower clip in dB (default -80); None disables it.

Returns:

dB weights, same shape as frequencies (a float for scalar input).

Return type:

float | numpy.ndarray[float64]

audio_samples.features.c_weighting(frequencies, *, min_db=-80.0)

The C-weighting of a set of frequencies in dB.

Parameters:
  • frequencies (float | array_like) – Frequencies in Hz.

  • min_db (Optional[float]) – Lower clip in dB (default -80); None disables it.

Returns:

dB weights, same shape as frequencies (a float for scalar input).

Return type:

float | numpy.ndarray[float64]

audio_samples.features.d_weighting(frequencies, *, min_db=-80.0)

The D-weighting of a set of frequencies in dB.

Parameters:
  • frequencies (float | array_like) – Frequencies in Hz.

  • min_db (Optional[float]) – Lower clip in dB (default -80); None disables it.

Returns:

dB weights, same shape as frequencies (a float for scalar input).

Return type:

float | numpy.ndarray[float64]

audio_samples.features.z_weighting(frequencies, *, min_db=-80.0)

The Z-weighting of a set of frequencies in dB (flat, 0 dB).

Parameters:
  • frequencies (float | array_like) – Frequencies in Hz.

  • min_db (Optional[float]) – Lower clip in dB (default -80); None disables it.

Returns:

dB weights, same shape as frequencies (a float for scalar input).

Return type:

float | numpy.ndarray[float64]

audio_samples.features.frequency_weighting(frequencies, *, kind='A', min_db=None)

A frequency-weighting curve chosen by name.

Parameters:
  • frequencies (float | array_like) – Frequencies in Hz.

  • kind (str) – "A" (default), "B", "C", "D" or "Z".

  • min_db (Optional[float]) – Lower clip in dB. Default None (no clip).

Returns:

dB weights, same shape as frequencies.

Return type:

float | numpy.ndarray[float64]

Raises:

ValueError – For an unknown kind.

audio_samples.features.multi_frequency_weighting(frequencies, *, kinds='ZAC', min_db=None)

Several weighting curves stacked, one row per name in kinds.

Parameters:
  • frequencies (array_like) – Frequencies in Hz.

  • kinds (str | Sequence[str]) – Curve names, e.g. "ZAC" (default).

  • min_db (Optional[float]) – Lower clip in dB. Default None (no clip).

Returns:

shape (len(kinds), *frequencies.shape).

Return type:

numpy.ndarray[float64]

Raises:

ValueError – For an unknown curve name.

audio_samples.features.perceptual_weighting(S, frequencies, *, kind='A', ref=1.0, amin=1e-10, top_db=None)

Perceptually weighted dB spectrogram.

Computes power_to_db(S, ref, amin, top_db) + weighting(frequencies).

Parameters:
  • S (array_like) – Power spectrogram, (F, T) or (channels, F, T).

  • frequencies (array_like) – 1-D centre frequency of each bin (Hz).

  • kind (str) – Weighting curve, "A" (default) … "Z".

  • ref (float | "max" | numpy.max) – dB reference. Default 1.0.

  • amin (float) – Floor before the logarithm. Default 1e-10.

  • top_db (Optional[float]) – Dynamic range below the peak in dB (per channel). Default None (no floor).

Returns:

same shape as S, in dB.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For shape mismatches or invalid dB parameters.

Tonal

audio_samples.features.chroma_filterbank(*, sr, n_fft, n_chroma=12, tuning=0.0, ctroct=5.0, octwidth=2.0, norm=2.0, base_c=True)

The chroma filterbank (float64).

Parameters:
  • sr (float) – Sample rate (Hz).

  • n_fft (int) – FFT length.

  • n_chroma (int) – Number of chroma bins. Default 12.

  • tuning (float) – Tuning deviation from A440 in fractions of a chroma bin.

  • ctroct (float) – Centre of the octave-dominance window (octaves above A0). Default 5.0.

  • octwidth (Optional[float]) – Half-width of the octave weighting; None = flat. Default 2.0.

  • norm (Optional[float]) – Column normalisation (p-norm, numpy.inf), None to disable. Default 2.

  • base_c (bool) – Row 0 is C (True, default) or A.

Returns:

shape (n_chroma, 1 + n_fft // 2).

Return type:

numpy.ndarray[float64]

Raises:

ValueError – For invalid parameters.

audio_samples.features.normalize(S, *, norm=inf, axis=0, threshold=None, fill=None)

Scales every slice of an array to unit norm.

Parameters:
  • S (array_like) – Array of any shape (finite values).

  • norm (Optional[float]) – numpy.inf (max-abs, default), -numpy.inf (min-abs), 0 (count of non-zeros), p > 0 (Lp), or None (no-op).

  • axis (Optional[int]) – Axis along which norms are computed (default 0); None normalises the whole array.

  • threshold (Optional[float]) – Slices with a norm below this are “small” (default: the smallest positive normal float64).

  • fill (Optional[bool]) – Small slices: None leaves them, False zeroes them, True fills them with the unit-norm constant.

Returns:

same shape as S.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For an invalid norm/threshold/axis, fill=True with norm=0, or non-finite input.

audio_samples.features.pitch_tuning(frequencies, *, resolution=0.01, bins_per_octave=12)

Tuning offset of a set of frequencies relative to A440.

Parameters:
  • frequencies (array_like) – Frequencies in Hz; non-positive values are ignored.

  • resolution (float) – Histogram resolution in fractions of a bin, in (0, 1). Default 0.01.

  • bins_per_octave (int) – Bins per octave of the reference grid. Default 12.

Returns:

tuning in [-0.5, 0.5) fractions of a bin (0.0 for no input).

Return type:

float

Raises:

ValueError – If resolution is not in (0, 1).

audio_samples.features.chroma_stft_from_spectrogram(S, *, sr, norm=inf, n_fft=None, tuning=0.0, n_chroma=12, ctroct=5.0, octwidth=2.0, base_c=True)

Chromagram of a precomputed spectrogram.

Parameters:
  • S (array_like) – Power spectrogram (a magnitude spectrogram gives “energy” chroma), shape (1 + n_fft // 2, T) or (channels, 1 + n_fft // 2, T).

  • sr (float) – Sample rate (Hz). Required.

  • norm (Optional[float]) – Per-frame normalisation (default numpy.inf).

  • n_fft (Optional[int]) – FFT length; None infers 2 * (F - 1).

  • tuning (Optional[float]) – Tuning in fractions of a chroma bin; None estimates it from S.

  • n_chroma (int) – Number of chroma bins. Default 12.

  • ctroct – Filterbank parameters (see chroma_filterbank).

  • octwidth – Filterbank parameters (see chroma_filterbank).

  • base_c – Filterbank parameters (see chroma_filterbank).

Returns:

shape (n_chroma, T) or (channels, n_chroma, T).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters or a bin count that does not match n_fft.

audio_samples.features.piptrack_from_spectrogram(S, *, sr, n_fft=None, fmin=150.0, fmax=4000.0, threshold=0.1, ref=None)

Spectral peak tracking on a precomputed magnitude spectrogram.

Parameters:
  • S (array_like) – Magnitude spectrogram, (1 + n_fft // 2, T) or (channels, 1 + n_fft // 2, T).

  • sr (float) – Sample rate (Hz). Required.

  • n_fft (Optional[int]) – FFT length; None infers 2 * (F - 1).

  • fmin (float) – Lowest reported frequency (Hz). Default 150.

  • fmax (float) – Peaks must lie below this frequency (Hz). Default 4000.

  • threshold (float) – Relative threshold. Default 0.1.

  • ref (None | float | numpy.max | numpy.mean) – Threshold reference; None (default) = per-frame maximum, a number = absolute threshold.

Returns:

(pitches, magnitudes), both shaped like S; zero except at detected peaks.

Return type:

tuple[numpy.ndarray[float32 | float64], numpy.ndarray[float32 | float64]]

Raises:

ValueError – For invalid parameters or a bin count that does not match n_fft.

audio_samples.features.estimate_tuning_from_spectrogram(S, *, sr, n_fft=None, resolution=0.01, bins_per_octave=12, fmin=150.0, fmax=4000.0, threshold=0.1, ref=None)

Tuning estimate from a precomputed spectrogram.

Parameters:
  • S (array_like) – Magnitude or power spectrogram, (F, T) or (channels, F, T) (all channels are pooled).

  • sr (float) – Sample rate (Hz). Required.

  • n_fft (Optional[int]) – FFT length; None infers 2 * (F - 1).

  • resolution (float) – Resolution in fractions of a bin. Default 0.01.

  • bins_per_octave (int) – Bins per octave of the grid. Default 12.

  • fmin – piptrack parameters.

  • fmax – piptrack parameters.

  • threshold – piptrack parameters.

  • ref – piptrack parameters.

Returns:

tuning in [-0.5, 0.5) fractions of a bin.

Return type:

float

Raises:

ValueError – For invalid parameters.

audio_samples.features.estimate_tuning_from_signal(y, *, sr, n_fft=2048, resolution=0.01, bins_per_octave=12, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant', fmin=150.0, fmax=4000.0, threshold=0.1, ref=None)

Tuning estimate from a signal.

Parameters:
  • y (array_like) – Signal, (n,) or (channels, n) (channels are pooled).

  • sr (float) – Sample rate (Hz). Required.

  • n_fft (int) – FFT length. Default 2048.

  • resolution (float) – Resolution in fractions of a bin. Default 0.01.

  • bins_per_octave (int) – Bins per octave of the grid. Default 12.

  • hop_length – STFT parameters of the spectrogram passed to piptrack.

  • win_length – STFT parameters of the spectrogram passed to piptrack.

  • window – STFT parameters of the spectrogram passed to piptrack.

  • center – STFT parameters of the spectrogram passed to piptrack.

  • pad_mode – STFT parameters of the spectrogram passed to piptrack.

  • fmin – piptrack parameters.

  • fmax – piptrack parameters.

  • threshold – piptrack parameters.

  • ref – piptrack parameters.

Returns:

tuning in [-0.5, 0.5) fractions of a bin.

Return type:

float

Raises:

ValueError – For invalid parameters or a signal too short for an uncentred STFT.

Constant-Q

audio_samples.features.cq_to_chroma(n_input, *, bins_per_octave=12, n_chroma=12, fmin=None, window=None, base_c=True)

The CQT-to-chroma folding matrix (float64).

Parameters:
  • n_input (int) – Number of CQT bins.

  • bins_per_octave (int) – CQT bins per octave (a multiple of n_chroma). Default 12.

  • n_chroma (int) – Number of chroma bins. Default 12.

  • fmin (Optional[float]) – Frequency of CQT bin 0 (Hz); None = C1.

  • window (Optional[array_like]) – Smooths each row by convolution with these weights.

  • base_c (bool) – Chroma row 0 is C (default) or A.

Returns:

shape (n_chroma, n_input) of zeros and ones.

Return type:

numpy.ndarray[float64]

Raises:

ValueError – For invalid parameters.

audio_samples.features.wavelet(*, freqs, sr, window='hann', filter_scale=1.0, pad_fft=True, norm=1.0, gamma=0.0, alpha=None)

Constant-Q / variable-Q wavelet filters.

Parameters:
  • freqs (array_like) – Centre frequencies in Hz, as for wavelet_lengths.

  • sr (float) – Sample rate. Required.

  • window – Named window. Default "hann".

  • filter_scale (float) – Filter-length scale. Default 1.

  • pad_fft (bool) – Centre the filters in a power-of-two buffer. Default True.

  • norm (Optional[float]) – Per-filter normalisation (p-norm). Default 1.

  • gamma (Optional[float]) – Bandwidth offset (Hz). Default 0.

  • alpha (Optional[float | array_like]) – As wavelet_lengths.

Returns:

(filters, lengths), complex128 filters of shape (len(freqs), width) and float64 lengths.

Return type:

tuple[numpy.ndarray[complex128], numpy.ndarray[float64]]

Raises:

ValueError – For invalid frequencies or parameters.

audio_samples.features.wavelet_lengths(*, freqs, sr, window='hann', filter_scale=1.0, gamma=0.0, alpha=None)

Fractional lengths of constant-Q / variable-Q wavelet filters.

Parameters:
  • freqs (array_like) – Centre frequencies in Hz, ascending: at least two, or one when alpha is given.

  • sr (float) – Sample rate. Required.

  • window – Window (named; see spectral.get_window). Default "hann".

  • filter_scale (float) – Filter-length scale. Default 1.

  • gamma (Optional[float]) – Bandwidth offset (Hz); 0 (default) = constant Q, None = ERB-derived.

  • alpha (Optional[float | array_like]) – Relative bandwidth, one value or one per frequency. None derives it from the spacing of the frequencies.

Returns:

(lengths, cutoff): the length of each filter in samples and the highest cut-off frequency in Hz.

Return type:

tuple[numpy.ndarray[float64], float]

Raises:

ValueError – For invalid frequencies or parameters.

audio_samples.features.chroma_cens_from_chroma(chroma, *, norm=2.0, win_len_smooth=41, smoothing_window='hann')

Chroma Energy Normalized Statistics (CENS) from a chromagram: the quantisation, smoothing and normalisation steps of AudioSamples.chroma_cens.

Parameters:
  • chroma (array_like) – Chromagram, (n_chroma, T) or (channels, n_chroma, T).

  • norm (Optional[float]) – Final per-frame normalisation. Default 2.

  • win_len_smooth (Optional[int]) – Smoothing length in frames; None disables. Default 41.

  • smoothing_window – Smoothing window. Default "hann".

Returns:

same shape as chroma.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters; RuntimeError for non-finite input.

audio_samples.features.tonnetz_from_chroma(chroma)

Tonal centroid features (tonnetz) from a chromagram.

Parameters:

chroma (array_like) – Chromagram, (n_chroma, T) or (channels, n_chroma, T).

Returns:

shape (6, T) or (channels, 6, T).

Return type:

numpy.ndarray[float32 | float64]

Raises:

RuntimeError – For non-finite input.

Pitch tracking and harmonics

audio_samples.features.yin(y, *, fmin, fmax, sr, frame_length=2048, hop_length=None, trough_threshold=0.1, center=True, pad_mode='constant')

Frame-wise YIN fundamental frequency of an array.

Parameters:
  • y (array_like) – Signal, (n,) or (channels, n).

  • fmin (float) – Lowest frequency searched (Hz). Required.

  • fmax (float) – Highest frequency searched (Hz). Required.

  • sr (float) – Sample rate. Required.

  • frame_length (int) – Samples per frame. Default 2048.

  • hop_length (Optional[int]) – None = frame_length // 4.

  • trough_threshold (float) – Absolute CMND threshold. Default 0.1.

  • center (bool) – Centre frames on t * hop_length. Default True.

  • pad_mode (str) – Padding for center. Default "constant".

Returns:

f0 in Hz, shape (n_frames,) or (channels, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters or a too-short signal.

audio_samples.features.pyin(y, *, fmin, fmax, sr, frame_length=2048, hop_length=None, n_thresholds=100, beta_parameters=(2, 18), boltzmann_parameter=2, resolution=0.1, max_transition_rate=35.92, switch_prob=0.01, no_trough_prob=0.01, fill_na=nan, center=True, pad_mode='constant', transition_min_prob=0.0001)

Probabilistic YIN of an array: f0 tracking with voicing decisions.

Parameters:
  • y (array_like) – Signal, (n,) or (channels, n).

  • fmin (float) – Search range in Hz. Required.

  • fmax (float) – Search range in Hz. Required.

  • sr (float) – Sample rate. Required.

  • frame_length (int) – Default 2048.

  • hop_length (Optional[int]) – None = frame_length // 4.

  • n_thresholds (int) – Default 100.

  • beta_parameters (tuple[float, float]) – Beta prior. Default (2, 18).

  • boltzmann_parameter (float) – Default 2.

  • resolution (float) – Pitch-bin width in semitones. Default 0.1.

  • max_transition_rate (float) – Octaves per second. Default 35.92.

  • switch_prob (float) – Voicing switch probability. Default 0.01.

  • no_trough_prob (float) – Default 0.01.

  • fill_na (Optional[float]) – f0 of unvoiced frames: NaN (default), None (best-guess pitch) or a number.

  • center (bool) – Default True.

  • pad_mode (str) – Default "constant".

  • transition_min_prob (Optional[float]) – Viterbi pruning threshold (None or 0 = exact). Default 1e-4.

Returns:

(f0, voiced_flag, voiced_prob), each (n_frames,) or (channels, n_frames); voiced_flag is bool, the others in y’s precision.

Return type:

tuple

Raises:

ValueError – For invalid parameters or a too-short signal.

audio_samples.features.salience(S, *, freqs, harmonics, weights=None, aggregate=None, filter_peaks=True, fill_value=nan, kind='linear', axis=-2)

Harmonic salience of a spectrogram: the weighted sum of the energy at the harmonics of every bin.

Parameters:
  • S (array_like) – Non-negative magnitudes, (F, T) or (channels, F, T).

  • freqs (array_like) – Bin frequencies: 1-D (F,) or shaped like S (time-varying).

  • harmonics (Sequence[float]) – Harmonic multipliers (1 is S itself).

  • weights (Optional[array_like]) – One weight per harmonic (weighted average).

  • aggregate – None / numpy.average (default), numpy.mean, numpy.sum, numpy.max, numpy.min, numpy.median.

  • filter_peaks (bool) – Keep only local maxima along frequency. Default True.

  • fill_value (float) – Value of non-peaks. Default NaN.

  • kind (str) – Must be "linear".

  • axis (int) – Must be -2.

Returns:

same shape as S.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For shape mismatches or unsupported options.

audio_samples.features.interp_harmonics(x, *, freqs, harmonics, kind='linear', fill_value=0, axis=-2)

Energy of a spectrogram interpolated at the harmonics of every bin.

Parameters:
  • x (array_like) – Energy, (F, T) or (channels, F, T).

  • freqs (array_like) – 1-D bin frequencies or an array shaped like x.

  • harmonics (array_like) – Harmonic multipliers.

  • kind (str | int) – Interpolation kind, as arrays.interp1d. Default "linear".

  • fill_value (float) – Value outside the frequency range. Default 0.

  • axis (int) – The frequency axis. Default -2.

Returns:

shape (len(harmonics), F, T) or (channels, len(harmonics), F, T).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For shape mismatches or unsupported options.

audio_samples.features.f0_harmonics(x, *, f0, freqs, harmonics, kind='linear', fill_value=0, axis=-2)

Energy at the harmonics of a time-varying f0.

Parameters:
  • x (array_like) – Energy, (F, T) or (channels, F, T).

  • f0 (array_like) – Fundamental per frame, (T,) or (channels, T); NaN frames get fill_value.

  • freqs (array_like) – 1-D bin frequencies or an array shaped like x.

  • harmonics (array_like) – Harmonic multipliers.

  • kind (str) – The interpolant, as for arrays.interp1d. Default "linear".

  • fill_value (float) – Value for out-of-range targets. Default 0.

  • axis (int) – The frequency axis. Default -2.

Returns:

shape (len(harmonics), T) or (channels, len(harmonics), T).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For shape mismatches or unsupported options.

Tuning, octave and key conversions (audio_samples.utils)

Vectorised: a scalar gives a Python float, an array-like an array of the same shape.

audio_samples.utils.hz_to_octs(frequencies, *, tuning=0.0, bins_per_octave=12)

Converts frequencies (Hz) to fractional octave numbers. Octave 0 is A0 (27.5 Hz for A440 tuning), so A4 is octave 4.0.

Parameters:
  • frequencies (float | array_like) – Frequencies in Hz.

  • tuning (float) – Tuning deviation from A440 in fractions of a bin. Default 0.

  • bins_per_octave (int) – Bins per octave the tuning refers to. Default 12.

Returns:

octave numbers, same shape as the input.

Return type:

float | numpy.ndarray[float64]

audio_samples.utils.octs_to_hz(octs, *, tuning=0.0, bins_per_octave=12)

Converts fractional octave numbers to frequencies (Hz), the inverse of hz_to_octs.

Parameters:
  • octs (float | array_like) – Octave numbers.

  • tuning (float) – Tuning deviation in fractions of a bin. Default 0.

  • bins_per_octave (int) – Default 12.

Returns:

frequencies in Hz, same shape as the input.

Return type:

float | numpy.ndarray[float64]

audio_samples.utils.a4_to_tuning(A4, *, bins_per_octave=12)

Converts an A4 reference frequency to a tuning deviation in fractions of a bin.

Parameters:
  • A4 (float | array_like) – Reference frequency of A4 in Hz.

  • bins_per_octave (int) – Default 12.

Returns:

tuning, same shape as the input.

Return type:

float | numpy.ndarray[float64]

audio_samples.utils.tuning_to_a4(tuning, *, bins_per_octave=12)

Converts a tuning deviation (fractions of a bin) to the A4 reference frequency.

Parameters:
  • tuning (float | array_like) – Tuning deviation.

  • bins_per_octave (int) – Default 12.

Returns:

A4 in Hz, same shape as the input.

Return type:

float | numpy.ndarray[float64]

audio_samples.utils.cqt_frequencies(n_bins, *, fmin, bins_per_octave=12, tuning=0.0)

Centre frequencies of a constant-Q filterbank.

Parameters:
  • n_bins (int) – Number of bins.

  • fmin (float) – Frequency of the first bin (Hz, before tuning). Required.

  • bins_per_octave (int) – Default 12.

  • tuning (float) – Tuning deviation in fractions of a bin. Default 0.

Returns:

shape (n_bins,).

Return type:

numpy.ndarray[float64]

audio_samples.utils.key_to_notes(key, *, unicode=True, natural=False)

Spells the 12 pitch classes for a key.

Parameters:
  • key (str) – A key such as "C:maj", "F#:min", "Bb:dorian".

  • unicode (bool) – Use ♯ / ♭ (default True) instead of # / b.

  • natural (bool) – Mark naturals with ♮ (or n). Default False.

Returns:

12 note names, starting from C.

Return type:

list[str]

Raises:

ValueError – For an unparsable key.

audio_samples.utils.key_to_degrees(key)

Pitch classes (0 = C) of the 7 scale degrees of a key.

Parameters:

key (str) – A key such as "C:maj" or "A:min".

Returns:

shape (7,).

Return type:

numpy.ndarray[int64]

Raises:

ValueError – For an unparsable key.