AudioSamples Core

The AudioSamples class is the core of the library. It stores the samples together with their sample rate, channel layout and sample format, so these do not have to be passed alongside the data.

AudioSamples Class

The main audio processing class. It supports several sample formats. All methods preserve the audio properties, and the arithmetic operators are overloaded to work on the samples. a == b is True when both have the same sample type, sample rate, channel count and length, and every sample is equal.

Key Features

Constructors and Factory Methods
  • Create audio from NumPy arrays with automatic type detection

  • Generate zero-filled or ones-filled audio in multiple formats (i16, i32, f32, f64)

  • Create uniform-value audio with specified sample values

Audio Editing and Manipulation
  • Concatenate multiple audio segments end-to-end

  • Stack mono sources into multi-channel audio

  • Repeat, trim, pad, and split audio with precise timing

  • Mix multiple audio sources with optional weights

  • Apply fade-in and fade-out effects with multiple curve types

Channel Operations
  • Pan stereo audio left/right with precise control

  • Balance stereo channels independently

  • Convert between mono and stereo with various methods

  • Extract individual channels or swap channel positions

Spectral Analysis and Transforms
  • Short-Time Fourier Transform (STFT) with configurable windows

  • Inverse STFT for signal reconstruction

  • Magnitude and phase spectrograms with multiple scaling options

  • Mel-frequency spectrograms and MFCC features

  • Chroma features for harmonic analysis

  • Frame-wise stft_matrix, istft_matrix, spectrogram_matrix, melspectrogram and mfcc_frames returning (channels, F, T) arrays (see Spectral Analysis)

Audio Processing
  • High-quality resampling with configurable quality levels

  • Window function application for signal processing

  • Sample rate conversion by exact ratios

Pitch Analysis
  • YIN algorithm for fundamental frequency detection

  • Time-based pitch tracking with multiple detection methods

  • Configurable frequency range and threshold parameters

Audio Decomposition
  • Harmonic-Percussive Source Separation (HPSS)

  • Configurable median filter sizes and mask softness

Digital Filtering
  • Butterworth filters (lowpass, highpass, bandpass)

  • Simple filters with cutoff frequency control

  • IIR filter design and application

  • Chebyshev Type I filters with passband ripple control

Statistics and Analysis
  • Peak, minimum, and maximum sample values

  • Mean, RMS, variance, and standard deviation

  • Zero crossing detection and rate calculation

  • Autocorrelation analysis with configurable lag

  • Spectral centroid and rolloff calculations

Amplitude Processing
  • Amplitude scaling with precise factor control

  • Normalization with multiple methods (peak, minmax, RMS)

  • Hard clipping (clamping samples to a range)

  • DC offset removal for signal cleanup

Dynamic Range Processing
  • Compression with configurable threshold, ratio, and timing

  • Limiting with lookahead and release control

  • Noise gating for signal cleanup

  • Expansion for dynamic range enhancement

Equalization
  • Parametric equalizer with multiple band support

  • Peak, low-shelf, and high-shelf filters

  • Three-band EQ with configurable frequencies

  • Real-time frequency response calculation

File Format Support
  • Multiple sample formats: i16, i24, i32, f32, f64

  • Automatic format detection and conversion

  • Type-safe casting between sample formats

NumPy Integration
  • Operator overloading for arithmetic

  • Support for numpy universal functions

  • Automatic property preservation through all operations

Filter and EQ Configuration Classes

IirFilterDesign

Configuration class for Infinite Impulse Response filters supporting:

  • Butterworth, Chebyshev Type I/II, and Elliptic filter types

  • Lowpass, highpass, bandpass, and bandstop responses

  • Configurable filter order and cutoff frequencies

EqBand

Individual equalizer band configuration with:

  • Peak, lowshelf, highshelf, lowpass, highpass, and bandpass types

  • Center/cutoff frequency specification in Hz

  • Gain control in dB with positive/negative values

  • Q factor for bandwidth control

ParametricEq

Multi-band parametric equalizer supporting:

  • Multiple EQ bands with independent configuration

  • Real-time frequency response calculation

  • Bands applied as a cascade of filters

API Reference

class audio_samples.AudioSamples

Bases: object

Represents homogeneous audio samples with associated metadata.

Primary container for audio data combining raw sample values with essential metadata including sample rate, channel layout, and type information. Supports both mono and multi-channel audio with unified interface.

The frame-wise analysis methods (stft_matrix, melspectrogram, chroma_stft, cqt, onset_strength, yin, …) return float32 / complex64 arrays for uint8, int16, int24 and float32 audio, and float64 / complex128 arrays for int32 and float64 audio: the smallest float type that holds every sample value exactly. Audio-returning methods keep the sample type.

add_numpy_array(numpy_array)
amplitude()

Return the peak (maximum absolute value) across all samples and channels.

Alias for peak, provided to match the conventional term “amplitude” used in some audio contexts.

Returns:

Maximum absolute amplitude present in the buffer.

Return type:

int | float

amplitude_envelope()

Compute a rectified amplitude envelope.

Returns:

Envelope array shaped like the input (channels by samples).

Return type:

numpy.ndarray

Raises:

AudioError – If envelope computation fails.

analytic_envelope()

Compute the analytic envelope via the Hilbert transform.

Returns:

Instantaneous amplitude shaped like the input.

Return type:

numpy.ndarray

Raises:

AudioError – If envelope computation fails.

apply_bessel_bandpass(order, low_frequency, high_frequency)

Apply a Bessel band-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Prototype filter order per edge; must be greater than zero.

  • low_frequency (float) – Lower band edge in hertz.

  • high_frequency (float) – Upper band edge in hertz.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_bessel_bandstop(order, low_frequency, high_frequency)

Apply a Bessel band-stop filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Prototype filter order per edge; must be greater than zero.

  • low_frequency (float) – Lower band edge in hertz.

  • high_frequency (float) – Upper band edge in hertz.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_bessel_highpass(order, cutoff_frequency)

Apply a Bessel high-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • cutoff_frequency (float) – -3 dB cutoff frequency in hertz.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_bessel_lowpass(order, cutoff_frequency)

Apply a Bessel low-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Bessel filters have a maximally flat group delay in the passband, preserving the wave shape of in-band signals. The cutoff is the -3 dB point.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • cutoff_frequency (float) – -3 dB cutoff frequency in hertz.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_butterworth_bandpass(order, low_frequency, high_frequency)

Apply a Butterworth band-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • low_frequency (float) – Lower cutoff frequency in hertz.

  • high_frequency (float) – Upper cutoff frequency in hertz.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero.

  • AudioError – If filter design or application fails.

apply_butterworth_highpass(order, cutoff_frequency)

Apply a Butterworth high-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • cutoff_frequency (float) – Cutoff frequency in hertz.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero.

  • AudioError – If filter design or application fails.

apply_butterworth_lowpass(order, cutoff_frequency)

Apply a Butterworth low-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • cutoff_frequency (float) – Cutoff frequency in hertz.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero.

  • AudioError – If filter design or application fails.

apply_chebyshev_i(order, cutoff_frequency, passband_ripple, response)

Apply a Chebyshev Type I filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • cutoff_frequency (float) – Cutoff frequency in hertz.

  • passband_ripple (float) – Maximum ripple within the passband in decibels.

  • response (FilterResponse | str) – 'lowpass' or 'highpass'. For band designs use IirFilterDesign.chebyshev_i_band() with apply_iir_filter().

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero.

  • AudioError – If filter design or application fails.

apply_chebyshev_ii_bandpass(order, low_frequency, high_frequency, stopband_attenuation)

Apply a Chebyshev Type II band-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Prototype filter order per edge; must be greater than zero.

  • low_frequency (float) – Lower band edge in hertz.

  • high_frequency (float) – Upper band edge in hertz.

  • stopband_attenuation (float) – Minimum stopband attenuation in decibels; must be positive.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_chebyshev_ii_bandstop(order, low_frequency, high_frequency, stopband_attenuation)

Apply a Chebyshev Type II band-stop filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Prototype filter order per edge; must be greater than zero.

  • low_frequency (float) – Lower band edge in hertz.

  • high_frequency (float) – Upper band edge in hertz.

  • stopband_attenuation (float) – Minimum stopband attenuation in decibels; must be positive.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_chebyshev_ii_highpass(order, cutoff_frequency, stopband_attenuation)

Apply a Chebyshev Type II high-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • cutoff_frequency (float) – Stopband edge frequency in hertz.

  • stopband_attenuation (float) – Minimum stopband attenuation in decibels; must be positive.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_chebyshev_ii_lowpass(order, cutoff_frequency, stopband_attenuation)

Apply a Chebyshev Type II low-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Chebyshev Type II (inverse Chebyshev) filters have a maximally flat passband and equiripple stopband. They are specified by the stopband attenuation rather than passband ripple.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • cutoff_frequency (float) – Stopband edge frequency in hertz.

  • stopband_attenuation (float) – Minimum stopband attenuation in decibels (typically 20-80 dB); must be positive.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_compressor(compressor_config)

Apply a compressor configuration in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:

compressor_config (CompressorConfig) – Parameters controlling threshold, ratio, and timing.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If compression fails.

apply_compressor_sidechain(config, sidechain)

Apply sidechain compression, returning a new buffer.

The compressor’s gain reduction is driven by the level of sidechain rather than the main signal. Sidechain processing must be enabled on the configuration (set config.side_chain to an enabled SideChainConfig). The detector input is (1 - m) * main + m * sidechain with m = config.side_chain.external_mix, then the side-chain filters. A mono sidechain drives every channel; a multi-channel one must have as many channels as the main signal and drives them channel by channel.

Note

Unlike the other dynamics operations in this module, which modify the signal in place, this returns a new buffer; both signals are copied first.

Parameters:
  • config (CompressorConfig) – Compressor parameters with sidechain enabled.

  • sidechain (AudioSamples) – External control signal. Must match the main signal’s dtype and length.

Returns:

A new sidechain-compressed buffer.

Return type:

AudioSamples

Raises:
  • TypeError – If the main and sidechain dtypes differ.

  • ValueError – If sidechain is not enabled, the configuration is invalid, the lengths differ, or a multi-channel sidechain has a different channel count.

  • AudioError – If compression fails.

apply_elliptic_bandpass(order, low_frequency, high_frequency, passband_ripple, stopband_attenuation)

Apply an elliptic (Cauer) band-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Prototype filter order per edge; must be greater than zero.

  • low_frequency (float) – Lower band edge in hertz.

  • high_frequency (float) – Upper band edge in hertz.

  • passband_ripple (float) – Peak passband ripple in decibels; must be positive.

  • stopband_attenuation (float) – Minimum stopband attenuation in decibels; must be positive and greater than passband_ripple.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_elliptic_bandstop(order, low_frequency, high_frequency, passband_ripple, stopband_attenuation)

Apply an elliptic (Cauer) band-stop filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Prototype filter order per edge; must be greater than zero.

  • low_frequency (float) – Lower band edge in hertz.

  • high_frequency (float) – Upper band edge in hertz.

  • passband_ripple (float) – Peak passband ripple in decibels; must be positive.

  • stopband_attenuation (float) – Minimum stopband attenuation in decibels; must be positive and greater than passband_ripple.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_elliptic_highpass(order, cutoff_frequency, passband_ripple, stopband_attenuation)

Apply an elliptic (Cauer) high-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • cutoff_frequency (float) – Passband edge frequency in hertz.

  • passband_ripple (float) – Peak passband ripple in decibels; must be positive.

  • stopband_attenuation (float) – Minimum stopband attenuation in decibels; must be positive and greater than passband_ripple.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_elliptic_lowpass(order, cutoff_frequency, passband_ripple, stopband_attenuation)

Apply an elliptic (Cauer) low-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Elliptic filters are equiripple in both passband and stopband, giving the steepest transition for a given order. They are specified by both the passband ripple and the stopband attenuation.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • cutoff_frequency (float) – Passband edge frequency in hertz.

  • passband_ripple (float) – Peak passband ripple in decibels; must be positive.

  • stopband_attenuation (float) – Minimum stopband attenuation in decibels; must be positive and greater than passband_ripple.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero or a parameter is invalid.

  • AudioError – If filter design or application fails.

apply_eq_band(band)

Apply a single EQ band in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:

band (EqBand) – Parametric band definition to apply.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If filter application fails.

apply_expander(config)

Apply a downward expander in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:

config (ExpanderConfig) – Expander parameters controlling threshold, ratio, and timing.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If expansion fails.

apply_filter(coefficients)

Apply an FIR filter by “valid” linear convolution, returning a new buffer.

For taps h[0..M] and a channel x of N samples this computes

y[i] = sum_{k=0}^{M-1} h[k] * x[i + M - 1 - k], i = 0 .. N - M

i.e. only the N - M + 1 outputs where every tap overlaps the input. The result is numpy.convolve(x, h, mode='valid') applied to each channel independently. self is not modified.

convolve vs apply_filter: convolve() returns the full convolution of length N + M - 1 (numpy.convolve(..., 'full')) and takes another AudioSamples; apply_filter takes a coefficient array and returns only the valid part of length N - M + 1, so the output is shorter than the input by M - 1 samples. Output index i corresponds to input time i + M - 1; the filter’s group delay ((M - 1) / 2 samples for a symmetric, linear-phase filter) is not compensated. Filters with 160 or more taps use FFT convolution; the result is the same up to rounding.

Computation is carried out in float64 with float64 coefficients. Integer audio is filtered on its raw scale and the result is rounded to nearest and saturated to the sample type, so taps outside [-1, 1] work for every sample type.

Parameters:

coefficients (numpy.ndarray) – 1-D array-like of FIR taps h (non-empty, converted to float64). [1.0] leaves the signal unchanged.

Returns:

Filtered buffer with N - M + 1 samples per channel.

Return type:

AudioSamples

Raises:
  • ValueError – If coefficients is empty.

  • AudioParameterError – If the audio is shorter than the filter.

Examples

>>> import numpy as np, audio_samples as aus
>>> x = aus.AudioSamples.new_mono(np.array([1.0, 2.0, 3.0, 4.0, 5.0]), sample_rate=8000)
>>> x.apply_filter(np.array([1.0, 0.5])).to_numpy()
array([2.5, 4. , 5.5, 7. ])
apply_filter_in_place(coefficients)

Apply an FIR filter by “valid” convolution in place.

Modifies the signal in place and returns None (the NumPy array it was created from, if any, is left unchanged).

In-place twin of apply_filter() (same formula and conventions): the buffer is replaced by the N - M + 1 valid outputs, so it becomes M - 1 samples shorter.

Parameters:

coefficients (numpy.ndarray) – 1-D array-like of FIR taps (non-empty).

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If coefficients is empty.

  • AudioParameterError – If the audio is shorter than the filter.

apply_gate(config)

Apply a downward noise gate in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:

config (GateConfig) – Gate parameters controlling threshold, ratio, and timing.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If gating fails.

apply_high_shelf(frequency, gain_db, q_factor)

Apply a high-shelf filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • frequency (float) – Shelf corner frequency in hertz.

  • gain_db (float) – Gain adjustment in decibels.

  • q_factor (float) – Shelf slope parameter.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If filter application fails.

apply_iir_filter(design)

Apply an arbitrary IIR filter design in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:

design (IirFilterDesign) – Filter definition including coefficients and structure.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If filter application fails.

apply_limiter(config)

Apply a limiter configuration in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:

config (LimiterConfig) – Parameters controlling ceiling, attack, and release.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If limiting fails.

apply_limiter_sidechain(config, sidechain)

Apply sidechain limiting, returning a new buffer.

The limiter’s gain reduction ceiling is enforced based on the level of sidechain rather than the main signal. Sidechain processing must be enabled on the configuration. The detector input and the accepted channel combinations are as in apply_compressor_sidechain(); with isp_limiting the detector reads true peaks.

Note

Returns a new buffer rather than modifying the signal in place, as apply_compressor_sidechain() does.

Parameters:
  • config (LimiterConfig) – Limiter parameters with sidechain enabled.

  • sidechain (AudioSamples) – External control signal. Must match the main signal’s dtype and length.

Returns:

A new sidechain-limited buffer.

Return type:

AudioSamples

Raises:
  • TypeError – If the main and sidechain dtypes differ.

  • ValueError – If sidechain is not enabled, the configuration is invalid, the lengths differ, or a multi-channel sidechain has a different channel count.

  • AudioError – If limiting fails.

apply_low_shelf(frequency, gain_db, q_factor)

Apply a low-shelf filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • frequency (float) – Shelf corner frequency in hertz.

  • gain_db (float) – Gain adjustment in decibels.

  • q_factor (float) – Shelf slope parameter.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If filter application fails.

apply_parametric_eq(eq)

Apply a parametric equalizer configuration in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:

eq (ParametricEq) – Equalizer definition containing one or more bands.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If filter application fails.

apply_peak_filter(frequency, gain_db, q_factor)

Apply a parametric peak filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • frequency (float) – Center frequency in hertz.

  • gain_db (float) – Gain adjustment in decibels.

  • q_factor (float) – Quality factor controlling bandwidth.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If filter application fails.

apply_three_band_eq(config)

Apply a three-band equalizer in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:

config (ThreeBandEqConfig) – Three-band EQ configuration describing the low shelf, mid peak, and high shelf bands.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If filter application fails.

apply_window(window)

Apply a sample-wise window to the signal.

Each sample is multiplied by its float64 coefficient. Integer audio is multiplied on its raw scale and the products are rounded to nearest and saturated to the sample type, so fractional windows (Hann, Hamming, …) work for every sample type.

Parameters:

window (numpy.ndarray) – 1-D sequence of coefficients matching the audio length. Any real array-like is accepted (e.g. float32); it is converted to float64.

Returns:

New buffer of the same sample type with the window applied.

Return type:

AudioSamples

Raises:
  • ValueError – If the window length does not equal the audio length.

  • AudioError – If windowing fails.

as_f32()

Audio-aware conversion to float32; shorthand for to_format(SampleType.F32).

Float -1.0/+1.0 map to the integer minimum/maximum (asymmetric: int16 -32768/32767); see to_format(). Use cast_as_f32 for a raw numeric cast instead.

as_f64()

Audio-aware conversion to float64; shorthand for to_format(SampleType.F64).

Float -1.0/+1.0 map to the integer minimum/maximum (asymmetric: int16 -32768/32767); see to_format(). Use cast_as_f64 for a raw numeric cast instead.

as_i16()

Audio-aware conversion to int16; shorthand for to_format(SampleType.I16).

Float -1.0/+1.0 map to the integer minimum/maximum (asymmetric: int16 -32768/32767); see to_format(). Use cast_as_i16 for a raw numeric cast instead.

as_i32()

Audio-aware conversion to int32; shorthand for to_format(SampleType.I32).

Float -1.0/+1.0 map to the integer minimum/maximum (asymmetric: int16 -32768/32767); see to_format(). Use cast_as_i32 for a raw numeric cast instead.

as_u8()

Audio-aware conversion to uint8 (offset binary); shorthand for to_format(SampleType.U8).

Float -1.0/+1.0 map to the integer minimum/maximum (asymmetric: int16 -32768/32767); see to_format(). Use cast_as_u8 for a raw numeric cast instead.

attack_decay_envelope(follower, method)

Compute attack and decay envelopes using an envelope follower.

Parameters:
Returns:

Attack and decay envelopes shaped like the input.

Return type:

tuple[numpy.ndarray, numpy.ndarray]

Raises:

AudioError – If envelope computation fails.

autocorrelation(max_lag)

Compute the autocorrelation sequence up to a lag limit.

Uses the unbiased estimate r[k] = (1 / (N - k)) * sum_{n=0}^{N-1-k} x[n] * x[n + k] for lags 0..=min(max_lag, N - 1), first channel only. It is not normalised: r[0] is the mean square, not 1. Divide by r[0] for a normalised sequence; multiply r[k] by (N - k) / N for the biased estimate. r[k] * (N - k) is the raw sum sum_{n=0}^{N-1-k} x[n] * x[n + k].

Parameters:

max_lag (int) – Maximum lag to include; must be greater than zero.

Returns:

max_lag + 1 values (fewer for short

signals), or None if the FFT fails.

Return type:

Optional[list[float]]

Raises:

ValueError – If max_lag is zero.

balance(balance)

Adjust the stereo balance in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:

balance (float) – Balance offset; negative favors left, positive favors right.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If the balance adjustment fails.

band_pass_filter(low_cutoff_hz, high_cutoff_hz)

Apply a band-pass filter (first-order Butterworth prototype), returning a new buffer.

A second-order band-pass from the first-order Butterworth prototype by the bilinear transform, prewarped at both edges, run causally from a zero initial state. self is not modified.

Parameters:
  • low_cutoff_hz (float) – Lower -3 dB edge in hertz.

  • high_cutoff_hz (float) – Upper -3 dB edge in hertz.

Returns:

New buffer containing the filtered signal.

Return type:

AudioSamples

Raises:

AudioError – If filtering fails.

beat_track(*, hop_length=512, start_bpm=120.0, tightness=100, trim=False, bpm=None, prior=None, units='frames', sparse=True)

Tracks beats with the dynamic-programming beat tracker.

The onset envelope is onset_strength(hop_length=hop_length, aggregate=numpy.median).

Parameters:
  • hop_length (int) – Hop of the onset envelope. Default 512.

  • start_bpm (float) – Prior centre of the tempo estimate. Default 120.

  • tightness (float) – Tempo-consistency weight. Default 100.

  • trim (bool) – Remove weak leading/trailing beats. Default False.

  • bpm (Optional[float | array_like]) – Tempo to track at (one value or one per frame); None estimates it.

  • prior – Tempo prior (see tempo).

  • units (str) – "frames" (default), "samples" or "time".

  • sparse (bool) – Must be True.

Returns:

(tempo, beats): tempo is the estimate as a float64 array of shape (1,) (bpm unchanged when given, 0.0 for silence); beats is a 1-D int64 (frames/samples) or float64 (time) array.

Return type:

tuple

Raises:

ValueError – For multi-channel audio, invalid parameters or sparse=False.

borrow_channel(channel_index)

Return a single channel as a new mono buffer.

The underlying crate method borrow_channel returns a borrowed, lifetime-bound view into the buffer. Such views cannot be exposed to Python safely, so this binding copies the selected channel into an owned buffer before returning it.

Parameters:

channel_index (int) – Zero-based index of the channel to borrow. Ignored for mono audio.

Returns:

An owned mono buffer containing the selected channel.

Return type:

AudioSamples

Raises:

ValueError – If the channel index is out of range.

butterworth_bandpass(order, low_frequency, high_frequency)

Apply a Butterworth band-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • low_frequency (float) – Lower cutoff frequency in hertz.

  • high_frequency (float) – Upper cutoff frequency in hertz.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero.

  • AudioError – If filter design or application fails.

butterworth_highpass(order, cutoff_frequency)

Apply a Butterworth high-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • cutoff_frequency (float) – Cutoff frequency in hertz.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero.

  • AudioError – If filter design or application fails.

butterworth_lowpass(order, cutoff_frequency)

Apply a Butterworth low-pass filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • order (int) – Filter order; must be greater than zero.

  • cutoff_frequency (float) – Cutoff frequency in hertz.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:
  • ValueError – If order is zero.

  • AudioError – If filter design or application fails.

cast_as(dtype)

Cast to another sample type without audio-aware scaling.

Raw numeric cast: each value keeps its number (like numpy.ndarray.astype with saturation), with no rescaling between full-scale ranges. Float-to-integer casts truncate toward zero and saturate at the type’s limits, so float audio in [-1, 1] becomes mostly -1, 0 and 1; int16 16384 cast to float64 is 16384.0, not 0.5. Use to_format() / as_* for audio-aware conversion.

Parameters:

dtype (SampleType) – Target type, e.g. SampleType.F64.

Returns:

New buffer of the target type.

Return type:

AudioSamples

Examples

>>> import numpy as np, audio_samples as aus
>>> x = aus.AudioSamples.new_mono(np.array([16384, -32768], dtype=np.int16), sample_rate=8000)
>>> x.cast_as(aus.SampleType.F64).to_numpy()
array([ 16384., -32768.])
>>> x.to_format(aus.SampleType.F64).to_numpy()
array([ 0.50001526, -1.        ])
cast_as_f32()

Raw numeric cast to float32 (no rescaling); shorthand for cast_as(SampleType.F32). See cast_as(); use as_f32 for audio-aware conversion.

cast_as_f64()

Raw numeric cast to float64 (no rescaling); shorthand for cast_as(SampleType.F64). See cast_as(); use as_f64 for audio-aware conversion.

cast_as_i16()

Raw numeric cast to int16 (no rescaling); shorthand for cast_as(SampleType.I16). See cast_as(); use as_i16 for audio-aware conversion.

cast_as_i32()

Raw numeric cast to int32 (no rescaling); shorthand for cast_as(SampleType.I32). See cast_as(); use as_i32 for audio-aware conversion.

cast_as_u8()

Raw numeric cast to uint8 (no rescaling); shorthand for cast_as(SampleType.U8). See cast_as(); use as_u8 for audio-aware conversion.

channels

Alias for num_channels.

chroma(stft_params, chroma_params)

Compute chromagram (pitch-class energy) features.

Parameters:
  • stft_params (StftParams) – Parameters used to generate the STFT.

  • chroma_params (ChromaParams) – Configuration for chroma projection.

Returns:

Chromagram shaped (pitch_classes, frames).

Return type:

numpy.ndarray

Raises:

AudioError – If chroma computation fails.

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.

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.

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.

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".

clip(min_val, max_val)

Clamp samples in-place to the provided minimum and maximum.

Modifies the signal in place and returns None (the NumPy array it was created from, if any, is left unchanged).

Parameters:
  • min_val (float) – Lower bound for clamping.

  • max_val (float) – Upper bound for clamping.

Raises:

AudioError – If clamping fails or the bounds are invalid.

complex_onset_detection(config)

Detect onset times using the complex-domain method.

Parameters:

config (ComplexOnsetConfig) – Parameters controlling magnitude and phase processing.

Returns:

Onset times in seconds.

Return type:

list[float]

Raises:

AudioError – If onset detection fails.

classmethod concatenate(segments)

Concatenate multiple buffers end to end.

Parameters:

segments (list[AudioSamples]) – Non-empty list of buffers to join.

Returns:

Combined buffer spanning all segments.

Return type:

AudioSamples

Raises:
  • ValueError – If the segment list is empty.

  • TypeError – If segments differ in dtype or are not AudioSamples.

  • AudioError – If concatenation fails.

classmethod concatenate_owned(segments)

Concatenate multiple owned buffers end to end.

Behaves identically to concatenate(); it mirrors the crate’s owned-segment variant. All segments must share the same dtype, sample rate, and channel count.

Parameters:

segments (list[AudioSamples]) – Non-empty list of buffers to join.

Returns:

Combined buffer spanning all segments.

Return type:

AudioSamples

Raises:
  • ValueError – If the segment list is empty.

  • TypeError – If segments differ in dtype or are not AudioSamples.

  • AudioError – If concatenation fails.

constant_q_transform(params, hop_size)

Compute the Constant-Q Transform (CQT) of a mono signal.

Parameters:
  • params (CqtParams) – CQT configuration (bins per octave, number of octaves, minimum frequency).

  • hop_size (int) – Hop size in samples between successive frames; must be greater than zero.

Returns:

Complex CQT coefficients shaped (frequency_bins, time_frames).

Return type:

numpy.ndarray

Raises:
  • ValueError – If hop_size is zero.

  • AudioError – If the signal is multi-channel or the computation fails.

convolve(other)

Compute the linear convolution of this signal with another.

Both signals are converted to f64 internally. The result is mono and carries this signal’s sample rate, with length len(self) + len(other) - 1.

This is the full convolution (numpy.convolve(x, h, 'full')). For FIR filtering with a coefficient array, apply_filter() returns only the valid part, N - M + 1 samples (numpy.convolve(x, h, 'valid')).

Parameters:

other (AudioSamples) – Signal to convolve with. Must be mono and share this signal’s data type and sample rate.

Returns:

The convolved mono signal.

Return type:

AudioSamples

Raises:
  • AudioParameterError – If the two signals have different sample rates.

  • TypeError – If the two signals have different data types.

  • AudioError – If either signal is multi-channel or the FFT fails.

copy()
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).

cross_correlation(other, max_lag)

Compute the cross-correlation with another audio buffer.

Uses the same unbiased, unnormalised estimate as autocorrelation(): r[k] = (1 / (N - k)) * sum_n self[n] * other[n + k] for k = 0 .. max_lag.

Parameters:
  • other (AudioSamples) – Audio buffer to correlate against.

  • max_lag (int) – Maximum lag to include; must be greater than zero.

Returns:

Cross-correlation coefficients up to the requested lag.

Return type:

list[float]

Raises:
  • ValueError – If max_lag is zero.

  • AudioParameterError – If the sample rates or channel counts differ (the message names both values).

  • TypeError – If the buffers have different data types.

deconvolve(other, regularization=0.0)

Recover a system response by regularised spectral-division deconvolution.

Solves self = denominator (*) h for h. The regularization term (>= 0) is scaled by the denominator’s peak power to stabilise the division near spectral nulls. The result is mono at this signal’s sample rate.

Parameters:
  • other (AudioSamples) – The denominator signal. Must be mono and share this signal’s data type.

  • regularization (float) – Non-negative regularisation factor.

Returns:

The deconvolved mono signal.

Return type:

AudioSamples

Raises:
  • AudioParameterError – If the two signals have different sample rates.

  • TypeError – If the two signals have different data types.

  • AudioError – If either signal is multi-channel or the FFT fails.

deemphasis(*, coef=0.97)

De-emphasis y[n] = x[n] + coef * y[n - 1] of every channel (inverse of preemphasis).

Parameters:

coef (float) – Coefficient (not 3). Default 0.97.

Returns:

the filtered audio.

Return type:

AudioSamples

Raises:

ValueError – For a non-finite coef, coef == 3 or fewer than two samples.

deemphasis_in_place(*, coef=0.97)

In-place deemphasis.

deinterleave_channels()

Split a multi-channel buffer into individual mono buffers.

Channel 0 becomes element 0, channel 1 becomes element 1, and so on. For mono input a single-element list is returned. This is the inverse of interleave_channels().

Returns:

One owned mono buffer per input channel.

Return type:

list[AudioSamples]

Raises:

AudioError – If channel separation fails.

detect_beats(config)

Place beats on a fixed-tempo grid anchored at the strongest onset.

Computes an onset strength envelope, then walks forward and backward from the global onset peak in steps of one inter-beat interval at config.tempo_bpm (snapping to nearby onsets within the configured tolerance). The tempo is not estimated: the returned tempo_bpm echoes the configuration. For tempo estimation and dynamic-programming beat tracking use beat_track.

Parameters:

config (BeatTrackingConfig) – Parameters controlling tempo targets and onset detection.

Returns:

Result object containing estimated tempo, beat times, and metadata.

Return type:

BeatTrackingData

Raises:

AudioError – If beat tracking fails.

detect_onsets(config)

Detect onset times using the configured algorithm.

Parameters:

config (OnsetDetectionConfig) – Parameters controlling peak picking and preprocessing.

Returns:

Onset times in seconds.

Return type:

list[float]

Raises:

AudioError – If onset detection fails.

detect_onsets_spectral_flux(config)

Detect onset times using spectral flux.

Parameters:

config (SpectralFluxConfig) – Parameters configuring the flux computation and picker.

Returns:

Onset times in seconds.

Return type:

list[float]

Raises:

AudioError – If onset detection fails.

detect_pitch_autocorr(min_frequency, max_frequency)

Detect the fundamental frequency using autocorrelation.

Parameters:
  • min_frequency (float) – Minimum expected frequency in hertz.

  • max_frequency (float) – Maximum expected frequency in hertz.

Returns:

Detected pitch in hertz, or None when no stable pitch is found.

Return type:

float | None

Raises:

AudioError – If pitch detection fails.

detect_pitch_yin(threshold=0.1, min_frequency=50.0, max_frequency=2000.0)

Detect the fundamental frequency using the YIN algorithm.

Parameters:
  • threshold (float) – Absolute threshold on YIN’s cumulative mean normalised difference d’(tau), in [0, 1]. The first lag whose d’ dips below it is taken. Lower values are stricter (a deeper dip is required, so fewer false detections and more None); higher values are more permissive. 0.1-0.2 is typical.

  • min_frequency (float) – Minimum expected frequency in hertz.

  • max_frequency (float) – Maximum expected frequency in hertz.

Returns:

Detected pitch in hertz, or None when no stable pitch is found.

Return type:

float | None

Raises:

AudioError – If pitch detection fails.

div_numpy_array(numpy_array)
dtype

Returns the dtype as a string for Python property access

duplicate_to_channels(n_channels)

Duplicate the buffer into the requested number of channels.

Parameters:

n_channels (int) – Target channel count; must be greater than zero.

Returns:

New buffer with the duplicated channels.

Return type:

AudioSamples

Raises:

AudioError – If duplication fails or the channel count is invalid.

duration_milliseconds

Duration of the audio in milliseconds (duration_seconds * 1000).

duration_seconds

Duration of the audio in seconds.

Calculated as samples_per_channel / sample_rate.

Returns:

Duration in seconds.

Return type:

float

Examples

>>> audio = aus.AudioSamples.from_array(np.zeros(44100), 44100)
>>> audio.duration_seconds
1.0
>>> audio_3s = aus.AudioSamples.from_array(np.zeros(132300), 44100)
>>> audio_3s.duration_seconds
3.0
eq_band(band)

Apply a single EQ band, returning a new buffer.

Non-mutating twin of apply_eq_band(); leaves the current buffer unchanged.

Parameters:

band (EqBand) – Parametric band definition to apply.

Returns:

A new buffer with the band applied.

Return type:

AudioSamples

Raises:

AudioError – If filter application fails.

eq_frequency_response(eq, frequencies)

Compute the combined magnitude and phase response of a parametric EQ.

Evaluates each enabled band’s biquad filter at every requested frequency and combines the results (magnitudes multiplied, phases summed), applying the EQ’s output gain to the combined magnitude. Disabled bands are skipped. This is purely analytical and does not modify the audio.

Parameters:
  • eq (ParametricEq) – The equalizer whose response to evaluate.

  • frequencies (np.typing.NDArray[np.float64]) – Frequencies in hertz at which to evaluate the response.

Returns:

Linear magnitude (1.0 = unity gain) and phase (radians) arrays, each the same length as frequencies.

Return type:

tuple[np.typing.NDArray[np.float64], np.typing.NDArray[np.float64]]

Raises:

AudioError – If any enabled band fails to design a filter (e.g. a frequency above the Nyquist limit).

estimate_key(stft_params)

Estimate the musical key of the audio signal.

Parameters:

stft_params (StftParams) – Parameters controlling the underlying STFT analysis.

Returns:

Detected key, including tonic pitch class, mode (major/minor),

and confidence score.

Return type:

Key

Raises:

AudioError – If key estimation fails.

estimate_tempo(config)

Estimate the global tempo of the signal in beats per minute.

This runs the same onset and tempo analysis as detect_beats() but returns only the estimated tempo, skipping the per-beat tracking step.

Parameters:

config (BeatTrackingConfig) – Parameters controlling tempo targets and onset detection.

Returns:

Estimated tempo in beats per minute.

Return type:

float

Raises:

AudioError – If tempo estimation fails.

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.

explain(obj, *, f0_range=None, n_fft=None, n_mels=None)

Explain a configuration in the context of this signal.

Uses this signal’s sample rate, length (samples per channel) and channel count as context, so quantities such as frame counts, durations and “window shorter than a pitch period” warnings are computed for it.

Parameters:
  • obj – The configuration to explain (StftParams, SpectrogramParams, MelParams, MfccParams, WindowType, IirFilterDesign, EqBand, CompressorConfig, LimiterConfig, VadConfig or OnsetDetectionConfig).

  • f0_range (tuple[float, float] | None) – Expected fundamental-frequency range (lowest, highest) in Hz.

  • n_fft (int | None) – FFT size a MelParams will be combined with.

  • n_mels (int | None) – Number of mel bands an MfccParams will be combined with.

Returns:

The explanation.

Return type:

ExplainDoc

Raises:

TypeError – If obj is not one of the supported types.

Examples

>>> import audio_samples as aus
>>> audio = aus.sine_wave(440.0, 1.0, sample_rate=16000)
>>> params = aus.StftParams(n_fft=512, hop_size=256, window=aus.WindowType.hanning)
>>> doc = audio.explain(params)
>>> doc.quantity("Frequency resolution")
31.25
extract_channel(channel_index)

Extract a single channel from the buffer.

Parameters:

channel_index (int) – Zero-based index of the channel to extract.

Returns:

Buffer representing the selected channel.

Return type:

AudioSamples

Raises:

AudioError – If the channel index is out of range or extraction fails.

fade_in(duration_seconds, curve)

Apply an in-place fade-in envelope.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • duration_seconds (float) – Fade duration.

  • curve (FadeCurve) – Curve controlling the fade shape.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If the fade fails or parameters are invalid.

fade_out(duration_seconds, curve)

Apply an in-place fade-out envelope.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • duration_seconds (float) – Fade duration.

  • curve (FadeCurve) – Curve controlling the fade shape.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If the fade fails or parameters are invalid.

fft(n_fft)

Compute the Fast Fourier Transform (FFT) of the signal.

The spectrum is one-sided: only the n_fft // 2 + 1 non-negative frequency bins are returned, as numpy.fft.rfft(x, n_fft) per channel (the signal is zero-padded to n_fft, which must be at least the signal length; longer input raises an error). Bin k is at k * sample_rate / n_fft Hz.

Parameters:

n_fft (int) – FFT size in samples; must be greater than zero.

Returns:

Complex spectrum shaped (channels, n_fft // 2 + 1).

Return type:

numpy.ndarray

Raises:
  • ValueError – If n_fft is zero.

  • AudioError – If the FFT computation fails.

filtfilt(design)

Apply a zero-phase (forward-backward) IIR filter in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Filters the signal twice – once forward and once backward – so the net phase response is zero. This doubles the effective filter order and squares the magnitude response. Useful when phase distortion must be avoided (e.g. analysis or offline processing).

Parameters:

design (IirFilterDesign) – Filter definition to apply forward and backward.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If filter design or application fails.

fourier_tempogram(*, hop_length=512, win_length=384, center=True, window='hann')

Fourier tempogram of every channel.

Parameters:
  • hop_length (int) – Hop of the onset envelope. Default 512.

  • win_length (int) – STFT length in frames. Default 384.

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

  • window – Analysis window. Default "hann".

Returns:

shape (channels, win_length // 2 + 1, n_frames + 1) (centred); index [0] for the 2-D array of mono audio.

Return type:

numpy.ndarray[complex64 | complex128]

frames()

Iterate over time-aligned frames of the signal.

Each frame is a snapshot across all channels at a single time index, so the number of frames equals the number of samples per channel.

Note

The crate yields each frame as a borrowed view; this method copies each frame into a new owned NumPy array.

Returns:

One array per time index, each shaped

(1,) for mono audio or (channels, 1) for multi-channel audio.

Return type:

list[numpy.ndarray]

frequency_response(frequencies)

Deprecated: always returns a flat response.

Audio samples do not carry a filter. Use IirFilterDesign.frequency_response() or SosFilter.frequency_response() instead. Emits a DeprecationWarning.

Parameters:

frequencies (list[float]) – Frequencies in hertz.

Returns:

All-ones magnitudes and all-zero phases.

Return type:

tuple[list[float], list[float]]

static from_array(arr, sample_rate)

Create an AudioSamples instance from a NumPy array.

Parameters:
  • arr (numpy.ndarray) – Audio data as a 1D (mono) or 2D (multi-channel) array. For multi-channel audio, shape should be (channels, samples). Supported dtypes: int16, int32, float32, float64.

  • sample_rate (int) – Sample rate in Hz (e.g., 44100, 48000).

Returns:

A new audio samples object that wraps arr without copying it. In-place methods (apply_*, butterworth_*, filtfilt, …) therefore modify arr itself; pass arr.copy() or call copy() to keep the original. Read-only arrays are copied before the first in-place modification.

Return type:

AudioSamples

Raises:

TypeError – If array dtype is not supported or dimensions are invalid.

Examples

>>> import numpy as np
>>> import audio_samples as aus
>>> # Create mono audio
>>> mono = np.sin(2 * np.pi * 440 * np.linspace(0, 1, 44100)).astype(np.float32)
>>> audio = aus.AudioSamples.from_array(mono, sample_rate=44100)
>>> # Create stereo audio
>>> stereo = np.random.randn(2, 44100).astype(np.float32)
>>> audio = aus.AudioSamples.from_array(stereo, sample_rate=44100)
from_numpy_array_with_metadata(numpy_array)
gammatone_spectrogram(spec_params, erb_params, log_params=None)

Compute a gammatone spectrogram using ERB-scaled filters.

Parameters:
  • spec_params (SpectrogramParams) – Parameters controlling the underlying STFT.

  • erb_params (ErbParams) – Configuration for the ERB filterbank.

  • log_params (Optional[LogParams]) – Optional parameters for decibel conversion.

Returns:

Gammatone spectrogram shaped (bands, frames).

Return type:

numpy.ndarray

Raises:

AudioError – If spectrogram computation fails.

Notes

log_params.floor_db is an absolute floor in dB re 1, not a range below the maximum (as top_db is).

get_compression_curve(config, input_levels_db)

Compute the static compression input/output curve.

Maps each input level through the compressor’s static gain characteristic (threshold, ratio, knee) plus makeup gain. This is purely analytical and does not modify or use the audio content (no envelope following).

Parameters:
  • config (CompressorConfig) – Compressor parameters.

  • input_levels_db (np.typing.NDArray[np.float64]) – Non-empty array of input levels in dBFS to evaluate.

Returns:

Output levels in dBFS, one per input, in the same order.

Return type:

np.typing.NDArray[np.float64]

Raises:
  • ValueError – If input_levels_db is empty or the configuration is invalid.

  • AudioError – If the computation fails.

get_gain_reduction(config)

Compute the per-sample gain reduction the compressor would apply.

Passes the audio through the envelope follower and compression gain calculation, collecting the gain reduction (in dB) at every sample without modifying the signal. For multi-channel audio, only the first channel is analysed.

Parameters:

config (CompressorConfig) – Compressor parameters.

Returns:

Gain reduction values in dB (each >= 0.0), one per sample (first channel for multi-channel audio).

Return type:

np.typing.NDArray[np.float64]

Raises:

AudioError – If the configuration is invalid or processing fails.

static griffinlim_audio(S, *, sample_rate, n_iter=32, hop_length=None, win_length=None, n_fft=None, window='hann', center=True, length=None, pad_mode='constant', momentum=0.99, init='random', rng=0, dtype=None)

Reconstructs audio from a magnitude spectrogram with fast Griffin-Lim, returning AudioSamples.

This is a static method: AudioSamples.griffinlim_audio(S, sample_rate=sr). See audio_samples.effects.griffinlim for the arguments.

Parameters:
  • S (array_like) – (1 + n_fft // 2, n_frames) or (channels, 1 + n_fft // 2, n_frames) non-negative magnitude.

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

  • **kwargs – n_iter, hop_length, win_length, n_fft, window, center, length, pad_mode, momentum, init, rng as audio_samples.effects.griffinlim (rng defaults to the seed 0, so repeated calls give the same audio).

  • dtype (Optional[SampleType]) – Sample type of the returned audio. None (default) gives float32 audio for a float32 S and float64 audio for any other input. The reconstruction 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 one channel).

Return type:

AudioSamples

static 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".

harmonic(*, kernel_size=31, power=2.0, mask=False, margin=1.0, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

Harmonic component from median-filtering harmonic/percussive separation.

STFT, audio_samples.effects.hpss (median filtering + soft masks), inverse STFT to the input length. The hpss method is separate and blends the masks its own way.

Parameters:
  • kernel_size (int | tuple[int, int]) – Median filter lengths. Default 31.

  • power (float) – Mask exponent. Default 2.

  • mask (bool) – Must be False; the masks themselves are effects.hpss(S, mask=True).

  • margin (float | tuple[float, float]) – Margins (>= 1). Default 1.

  • n_fft – STFT parameters; window sets the STFT window.

  • hop_length – STFT parameters; window sets the STFT window.

  • win_length – STFT parameters; window sets the STFT window.

  • window – STFT parameters; window sets the STFT window.

  • center – STFT parameters; window sets the STFT window.

  • pad_mode – STFT parameters; window sets the STFT window.

Returns:

the harmonic component, same length.

Return type:

AudioSamples

harmonic_analysis(fundamental_freq, num_harmonics, tolerance, n_fft, window_type)

Measure harmonic amplitudes relative to a fundamental frequency.

Parameters:
  • fundamental_freq (float) – Fundamental frequency in hertz.

  • num_harmonics (int) – Number of harmonics to report; must be greater than zero.

  • tolerance (float) – Frequency tolerance expressed as a fraction of the harmonic.

  • n_fft (Optional[int]) – Optional FFT size in samples; must be greater than zero when provided.

  • window_type (Optional[WindowType]) – Optional window type applied before the FFT.

Returns:

Harmonic magnitudes ordered by harmonic index.

Return type:

list[float]

Raises:
  • ValueError – If num_harmonics or n_fft is zero.

  • AudioError – If the analysis fails.

harmonic_in_place(*, kernel_size=31, power=2.0, mask=False, margin=1.0, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

In-place harmonic; arguments as harmonic.

harmonic_percussive(*, kernel_size=31, power=2.0, mask=False, margin=1.0, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

Harmonic and percussive components from median-filtering separation (hpss is a separate method with its own mask blend).

Parameters:

harmonic. (As)

Returns:

(harmonic, percussive); with margins of 1 they sum to the input up to round-off.

Return type:

tuple[AudioSamples, AudioSamples]

harmonic_to_noise_ratio(fundamental_freq, num_harmonics, n_fft, window_type)

Estimate the harmonic-to-noise ratio around a fundamental frequency.

Parameters:
  • fundamental_freq (float) – Fundamental frequency in hertz.

  • num_harmonics (int) – Number of harmonics to evaluate; must be greater than zero.

  • n_fft (Optional[int]) – Optional FFT size in samples; must be greater than zero when provided.

  • window_type (Optional[WindowType]) – Optional window type applied before the FFT.

Returns:

Harmonic-to-noise ratio value.

Return type:

float

Raises:
  • ValueError – If num_harmonics or n_fft is zero.

  • AudioError – If the analysis fails.

high_pass_filter(cutoff_hz)

Apply a first-order Butterworth high-pass filter, returning a new buffer.

-3 dB at cutoff_hz, 6 dB/octave: the bilinear-transform design prewarped at cutoff_hz, run causally from a zero initial state. self is not modified.

Parameters:

cutoff_hz (float) – Cutoff frequency in hertz, in (0, Nyquist).

Returns:

New buffer containing the filtered signal.

Return type:

AudioSamples

Raises:

AudioError – If filtering fails.

hpss(config=None, median_filter_harmonic=None, median_filter_percussive=None, mask_softness=None, *, stft_params=None)

Separate harmonic and percussive components using median-filter HPSS.

Parameters:
  • config (StftParams | HpssConfig) – Either a complete HpssConfig (the remaining arguments must then be omitted), or the StftParams of the analysis STFT.

  • median_filter_harmonic (Optional[int]) – Harmonic (time-direction) median filter length in frames. Default 17. StftParams only.

  • median_filter_percussive (Optional[int]) – Percussive (frequency-direction) median filter length in bins. Default 17. StftParams only.

  • mask_softness (Optional[float]) – Mask softness in [0, 1] (0 = hard mask). Default 0.5. StftParams only.

  • stft_params (Optional[StftParams]) – Deprecated keyword alias of config (its name in audio_samples 0.2.x); emits a DeprecationWarning.

Returns:

(harmonic, percussive).

Return type:

tuple[AudioSamples, AudioSamples]

Raises:
  • TypeError – If config is neither StftParams nor HpssConfig, or filter arguments are given together with an HpssConfig.

  • ValueError – If the configuration is invalid.

Examples

>>> harmonic, percussive = audio.hpss(HpssConfig.musical)
>>> harmonic, percussive = audio.hpss(StftParams(2048, 512, WindowType.hanning, True))
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.

hybrid_tempogram(*, hop_length=512, win_length=384, center=True, window='hann')

Hybrid tempogram of every channel: the Fourier and autocorrelation tempograms combined on the Fourier tempo grid.

Parameters:
  • hop_length (int) – Hop of the onset envelope. Default 512.

  • win_length (int) – Window of both tempograms (>= 3). Default 384.

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

  • window – Window of both tempograms. Default "hann".

Returns:

shape (channels, win_length // 2 + 1, n_frames) on the fourier_tempo_frequencies grid; index [0] for the 2-D array of mono audio.

Return type:

numpy.ndarray[float32 | float64]

static 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.

iirt(*, win_length=2048, hop_length=None, center=True, tuning=0.0, pad_mode='constant', flayout='sos', res_type='soxr_hq', **kwargs)

The energy of each semitone band per frame.

Parameters:
  • win_length (int) – Frame length in samples. Default 2048.

  • hop_length (Optional[int]) – Samples between frames. Default win_length // 4.

  • center (bool) – Pad so that frames are centred. Default true.

  • tuning (float) – Deviation from A440 in fractions of a semitone.

  • pad_mode (str) – "constant", "edge", "reflect", "symmetric", "wrap".

  • flayout (str) – "sos" (default) or "ba".

  • res_type (str) – Resampler quality.

  • **kwargs – The filterbank’s parameters.

Returns:

(channels, 85, n_frames), float32 for u8, i16, I24 and f32 audio, otherwise float64.

Return type:

numpy.ndarray

info()

Get information about the audio samples. :returns: An object containing sample rate, channels, frames, duration, and layout. :rtype: AudioSamplesInfo

Examples

>>> import audio_samples as aus
>>> audio = aus.AudioSamples.from_array(np.random.randn(2, 44100).astype(np.float32), sample_rate=44100)
>>> info = audio.info()
static interleave_channels(channels)

Combine multiple mono buffers into a single multi-channel buffer.

The first buffer becomes channel 0, the second channel 1, and so on. All inputs must share the same dtype and number of samples; the output sample rate is taken from the first input.

Parameters:

channels (list[AudioSamples]) – Non-empty list of mono buffers, all of the same dtype and length.

Returns:

A multi-channel buffer with one channel per input.

Return type:

AudioSamples

Raises:

ValueError – If the list is empty, the dtypes differ, or the inputs do not all have the same sample count.

is_mono()
is_multi_channel()
classmethod istft(stft_result)

Invert a Short-Time Fourier Transform result.

Parameters:

stft_result (StftResult) – Output from stft to be reconstructed.

Returns:

Reconstructed time-domain signal.

Return type:

AudioSamples

Raises:

AudioError – If reconstruction fails.

static istft_matrix(stft_matrix, *, sample_rate, hop_length=None, win_length=None, n_fft=None, window='hann', center=True, length=None, dtype=None)

Reconstruct audio from an STFT matrix by weighted overlap-add.

This is a static method: AudioSamples.istft_matrix(D, sample_rate=sr).

Parameters:
  • stft_matrix (array_like) – complex array of shape (channels, 1 + n_fft // 2, n_frames) or (1 + n_fft // 2, n_frames) (treated as one channel).

  • sample_rate (int) – Sample rate of the returned audio (keyword-only).

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

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

  • n_fft (Optional[int]) – None infers 2 * (n_bins - 1).

  • window – Window used for analysis (see stft_matrix).

  • center (bool) – Whether the analysis frames were centred.

  • length (Optional[int]) – Exact output length per channel; pass the original length to undo the centre padding exactly.

  • dtype (Optional[SampleType]) – Sample type of the returned audio. None (default) gives float32 audio for a complex64 matrix and float64 audio for any other input. The inverse transform 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 – If the matrix is not 2-D/3-D, the bin count does not match n_fft, or parameters are invalid.

iter_channels()

Iterate over the complete signal of each channel.

Each item is the full temporal sequence of one channel, yielded in increasing channel-index order. Named iter_channels to avoid clashing with channels(), which returns the channel count.

Note

Channel iteration copies each channel into a new owned NumPy array.

Returns:

One mono array per channel, each shaped

(samples,).

Return type:

list[numpy.ndarray]

len

Total number of samples across all channels (same as len(audio)).

low_pass_filter(cutoff_hz)

Apply a first-order Butterworth low-pass filter, returning a new buffer.

-3 dB at cutoff_hz, 6 dB/octave: the bilinear-transform design prewarped at cutoff_hz, run causally from a zero initial state. self is not modified.

Parameters:

cutoff_hz (float) – Cutoff frequency in hertz, in (0, Nyquist).

Returns:

New buffer containing the filtered signal.

Return type:

AudioSamples

Raises:

AudioError – If filtering fails.

lpc(*, order)

LPC coefficients of every channel (Burg’s method).

Parameters:

order (int) – Prediction order; each channel needs more than order samples.

Returns:

shape (channels, order + 1), rows [1, a_1, ..., a_order]; mono audio gives one row (index [0] for a 1-D result).

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For a too-short or non-finite channel.

magnitude_difference_matrix(config)

Compute the complex-domain magnitude difference matrix.

Parameters:

config (ComplexOnsetConfig) – Parameters controlling magnitude and phase processing.

Returns:

Magnitude difference matrix with axes (frequency_bins, frames).

Return type:

numpy.ndarray

Raises:

AudioError – If matrix computation fails.

static magphase(complex_spect, power=None)

Decompose a complex spectrogram into magnitude and phase.

Given a complex matrix D, returns (magnitude, phase) such that D = magnitude * phase elementwise, where phase contains unit-magnitude complex factors. Bins where the magnitude is zero are assigned a phase of 1 + 0j.

This is a static method that operates on a complex spectrogram array (such as the output of fft or constant_q_transform) rather than on an AudioSamples instance.

Parameters:
  • complex_spect (numpy.ndarray) – Complex 2-D STFT or FFT matrix.

  • power (Optional[float]) – Exponent applied to the magnitude values, as numpy.abs(D) ** power; any number, fractional or negative. Defaults to 1 (raw magnitude).

Returns:

The real-valued magnitude matrix

and the complex unit-magnitude phase matrix.

Return type:

tuple[numpy.ndarray, numpy.ndarray]

max()

Compute the maximum sample value across all channels.

Returns:

Highest signed amplitude value found in the buffer.

Return type:

int | float

mean()

Calculate the arithmetic mean of the sample values.

Returns:

Mean amplitude across all samples and channels.

Return type:

float

median()

Return the value at the temporal midpoint, as midpoint_sample does.

Samples are selected by index position; the buffer is not sorted.

Returns:

The midpoint value if the view is non-empty, None otherwise.

Return type:

Optional[float]

mel_spectrogram(spec_params, mel_params, log_params=None)

Compute a mel-frequency spectrogram.

Parameters:
  • spec_params (SpectrogramParams) – Parameters controlling the underlying STFT.

  • mel_params (MelParams) – Configuration for the mel filterbank.

  • log_params (Optional[LogParams]) – Optional parameters for decibel conversion.

Returns:

Mel spectrogram shaped (mel_bins, frames). Without

log_params the values are sqrt(M @ |X|**2) (the square root of the mel power spectrogram, following the spectrograms crate), which is neither the mel power M @ |X|**2 nor the mel magnitude M @ |X|. For either of those use melspectrogram() with power=2 or power=1.

Return type:

numpy.ndarray

Raises:

AudioError – If spectrogram computation fails.

Notes

With M the mel filterbank and |X|**2 the STFT power:

  • without log_params the result is sqrt(M @ |X|**2), the square root of the mel power (not M @ |X|);

  • with log_params it is max(10*log10(M @ |X|**2), floor_db). floor_db is an absolute floor in dB re 1 (e.g. -80 clips values below -80 dB), not a range below the maximum like the top_db of power_to_db.

The mel scale is Slaney’s (linear below 1 kHz, logarithmic above). The filters are not normalised by default (MelParams(norm=None), triangles of peak 1); pass norm="slaney" for area normalisation.

melspectrogram(*, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='constant', power=2.0, n_mels=128, fmin=0.0, fmax=None, htk=False, norm='slaney')

Mel spectrogram of every channel: the mel filterbank applied to the STFT magnitude raised to power.

Parameters:
  • n_fft (int) – Default 2048.

  • hop_length (int) – Default 512.

  • win_length – As stft_matrix.

  • window – As stft_matrix.

  • center – As stft_matrix.

  • pad_mode – As stft_matrix.

  • power (float) – Exponent of the STFT magnitude; 2.0 (default) for power, 1.0 for magnitude.

  • n_mels (int) – Number of mel bands. Default 128.

  • fmin (float) – Lowest frequency (Hz). Default 0.

  • fmax (Optional[float]) – Highest frequency (Hz); None = sr / 2.

  • htk (bool) – HTK mel scale instead of Slaney (default False).

  • norm (None | "slaney" | float) – Filter normalisation. Default “slaney”.

Returns:

shape (channels, n_mels, n_frames); float32 for uint8, int16, int24 and float32 audio, float64 for int32 and float64 audio.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

mfcc(stft_params, n_mels, mfcc_params)

Compute mel-frequency cepstral coefficients (MFCCs).

Parameters:
  • stft_params (StftParams) – Parameters used to generate the STFT.

  • n_mels (int) – Number of mel bands; must be greater than zero.

  • mfcc_params (MfccParams) – Configuration for the cepstral projection.

Returns:

MFCC matrix shaped (coefficients, frames). This follows

the spectrograms crate’s MFCC; mfcc_frames() is the configurable pipeline (orthonormal DCT, optional lifter and dB floor).

Return type:

numpy.ndarray

Raises:
  • ValueError – If n_mels is zero.

  • AudioError – If the MFCC computation fails.

Notes

Pipeline: mel power spectrogram (Slaney scale, n_mels bands from 0 Hz to sample_rate / 2, no filter normalisation), then L = 10*log10(max(., 1e-8)), then an unnormalised DCT-II c[q] = sum_b L[b] * cos(pi*q*(b + 0.5)/n_mels) keeping the first n_mfcc coefficients, then the HTK sinusoidal lifter 1 + (22/2)*sin(pi*q/22) (lifter 22).

The result equals mfcc_frames (orthonormal DCT, no lifter, no dB floor) times s_q * lifter_q, with s_0 = sqrt(n_mels) and s_q = sqrt(n_mels / 2) for q >= 1.

mfcc_frames(*, n_mfcc=20, dct_type=2, norm='ortho', lifter=0.0, mel_norm='slaney', n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='constant', power=2.0, n_mels=128, fmin=0.0, fmax=None, htk=False, ref=1.0, amin=1e-10, top_db=None)

Mel-frequency cepstral coefficients of every channel.

The pipeline is melspectrogram -> power_to_db(ref, amin, top_db) -> DCT along the mel axis -> first n_mfcc rows -> optional liftering.

Parameters:
  • n_mfcc (int) – Number of coefficients. Default 20.

  • dct_type (int) – 1, 2 (default) or 3.

  • norm (Optional[str]) – DCT normalisation, "ortho" (default) or None.

  • lifter (float) – Liftering coefficient (0 disables). Default 0.

  • mel_norm (None | "slaney" | float) – Mel filter normalisation (norm of melspectrogram). Default “slaney”.

  • n_fft (default 512)

  • hop_length (default 512)

  • power – Passed to the mel spectrogram, as in melspectrogram.

  • n_mels – Passed to the mel spectrogram, as in melspectrogram.

  • fmin – Passed to the mel spectrogram, as in melspectrogram.

  • fmax – Passed to the mel spectrogram, as in melspectrogram.

  • htk – Passed to the mel spectrogram, as in melspectrogram.

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

  • amin (float) – dB floor before the log. Default 1e-10.

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

Returns:

shape (channels, n_mfcc, n_frames); float32 for uint8, int16, int24 and float32 audio, float64 for int32 and float64 audio.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters, including n_mfcc > n_mels.

midpoint_sample()

Return the value at the temporal midpoint of a mono signal.

median returns the same value. For even-length signals the result is the average of the two central samples; for odd-length signals the single central sample is returned. Samples are selected by index position; the buffer is not sorted.

Returns:

Midpoint value for mono audio, or None if the signal

is multi-channel.

Return type:

Optional[float]

min()

Compute the minimum sample value across all channels.

Returns:

Lowest signed amplitude value found in the buffer.

Return type:

int | float

classmethod mix(sources, weights=None)

Mix multiple buffers together with optional weights.

Parameters:
  • sources (list[AudioSamples]) – Non-empty list of buffers to mix.

  • weights (Optional[list[float]]) – Optional mixing weights, matching the number of sources.

Returns:

Mixed buffer containing the weighted sum.

Return type:

AudioSamples

Raises:
  • ValueError – If the source list is empty.

  • TypeError – If sources differ in dtype or are not AudioSamples.

  • AudioError – If mixing fails.

moving_average_envelope(window_size, hop_size)

Compute a moving-average envelope over the rectified signal.

Parameters:
  • window_size (int) – Number of samples per averaging window; must be greater than zero.

  • hop_size (int) – Step between windows in samples; must be greater than zero.

Returns:

Moving-average envelope shaped (channels, frames).

Return type:

numpy.ndarray

Raises:
  • ValueError – If window_size or hop_size is zero.

  • AudioError – If envelope computation fails.

mu_compress(mu)

Apply mu-law compression to the signal.

Parameters:

mu (float) – Mu parameter controlling the compression curve.

Returns:

New buffer containing the compressed samples.

Return type:

AudioSamples

Raises:

AudioError – If compression fails.

mu_expand(mu)

Apply mu-law expansion to the signal.

Parameters:

mu (float) – Mu parameter used during compression.

Returns:

New buffer containing the expanded samples.

Return type:

AudioSamples

Raises:

AudioError – If expansion fails.

mul_numpy_array(numpy_array)
ndim

1 for mono, 2 for multi-channel.

Type:

Number of array dimensions

static new_mono(arr, sample_rate)

Create mono audio from a 1-D NumPy array.

The array’s dtype becomes the sample type; no value conversion is performed (float samples are expected in [-1, 1], integer samples span the full integer range). Supported dtypes: uint8, int16, int32, float32, float64.

The returned object wraps arr without copying it (zero-copy). Methods that work in place (apply_compressor, apply_limiter, apply_iir_filter, filtfilt, reverse_in_place, …) therefore modify arr itself; pass arr.copy() to keep the original. Methods that return a new buffer, or that replace the buffer wholesale (e.g. scale), leave arr unchanged. Read-only arrays are copied before the first in-place modification.

Parameters:
  • arr (numpy.ndarray) – 1-D array of samples (non-empty).

  • sample_rate (int) – Sample rate in Hz.

Returns:

Mono audio viewing arr.

Return type:

AudioSamples

Raises:

Examples

>>> import numpy as np, audio_samples as aus
>>> a = np.zeros(4)
>>> x = aus.AudioSamples.new_mono(a, sample_rate=8000)
>>> x.num_channels, x.sample_rate
(1, 8000)
static new_multi(arr, sample_rate)

Create multi-channel audio from a 2-D (channels, samples) NumPy array.

Same conventions as new_mono(): the dtype becomes the sample type and no value conversion is performed. A (samples, channels)-shaped array triggers a warning.

The returned object wraps arr without copying it (zero-copy). Methods that work in place (apply_compressor, apply_limiter, apply_iir_filter, filtfilt, reverse_in_place, …) therefore modify arr itself; pass arr.copy() to keep the original. Methods that return a new buffer, or that replace the buffer wholesale (e.g. scale), leave arr unchanged. Read-only arrays are copied before the first in-place modification.

Parameters:
  • arr (numpy.ndarray) – 2-D array shaped (channels, samples).

  • sample_rate (int) – Sample rate in Hz.

Returns:

Multi-channel audio viewing arr.

Return type:

AudioSamples

Raises:

Examples

>>> import numpy as np, audio_samples as aus
>>> x = aus.AudioSamples.new_multi(np.zeros((2, 4), dtype=np.float32), sample_rate=8000)
>>> x.num_channels
2
normalize(min, max, method)

Normalize samples in-place using one of the supported strategies.

Modifies the signal in place and returns None (the NumPy array it was created from, if any, is left unchanged).

Parameters:
  • min (float) – Lower bound for the normalized output.

  • max (float) – Upper bound for the normalized output.

  • method (NormalizationMethod | str) – Strategy controlling the normalization.

Raises:

AudioError – If normalization fails.

num_channels

Number of audio channels.

Returns:

Number of channels (1 for mono, 2 for stereo, etc.).

Return type:

int

Examples

>>> mono_audio.num_channels
1
>>> stereo_audio.num_channels
2
nyquist()

Nyquist frequency in Hz (sample_rate / 2).

static ones_mono(length, sample_rate)
static ones_mono_f64(length, sample_rate)
static ones_mono_i16(length, sample_rate)
static ones_mono_i32(length, sample_rate)
static ones_multi(channels, length, sample_rate)
static ones_multi_f64(channels, length, sample_rate)
static ones_multi_i16(channels, length, sample_rate)
static ones_multi_i32(channels, length, sample_rate)
onset_detect(*, hop_length=512, backtrack=False, energy=None, units='frames', normalize=True, sparse=True, pre_max=None, post_max=None, pre_avg=None, post_avg=None, delta=None, wait=None, method='greedy')

Detects onsets by peak picking on the onset strength envelope.

The default onset envelope (onset_strength(hop_length=hop_length)) is normalised to [0, 1], peak-picked and optionally backtracked.

Parameters:
  • hop_length (int) – Hop of the onset envelope. Default 512.

  • backtrack (bool) – Move onsets back to the preceding local minimum of energy. Default False.

  • energy (Optional[array_like]) – 1-D function to backtrack on (one value per frame); None uses the normalised envelope.

  • units (str) – "frames" (default), "samples" or "time".

  • normalize (bool) – Scale the envelope to [0, 1]. Default True.

  • sparse (bool) – Must be True.

  • pre_max (Optional[int])

  • post_max (Optional[int])

  • pre_avg (Optional[int])

  • post_avg (Optional[int])

  • wait (Optional[int])

  • delta (Optional[float]), method (str) – Peak-picking parameters (see rhythm.peak_pick); None derives the value from the frame rate (30 ms / 100 ms windows, delta=0.07).

Returns:

1-D onset frames or samples (int64), or times (float64).

Return type:

numpy.ndarray

Raises:

ValueError – For multi-channel audio, invalid parameters or sparse=False.

onset_detection_function(config)

Compute the energy-based onset detection function.

Parameters:

config (OnsetDetectionConfig) – Parameters controlling the detection function.

Returns:

(times, values): frame times in

seconds first, then the detection-function value of each frame.

Return type:

tuple[list[float], list[float]]

Raises:

AudioError – If the detection function computation fails.

onset_detection_function_complex(config)

Compute the complex-domain onset detection function without peak picking.

Parameters:

config (ComplexOnsetConfig) – Parameters controlling magnitude and phase processing.

Returns:

Complex onset detection function values.

Return type:

list[float]

Raises:

AudioError – If detection function computation fails.

onset_strength(*, lag=1, max_size=1, detrend=False, center=True, aggregate=None, n_fft=2048, hop_length=512, win_length=None, window='hann', pad_mode='constant', power=2.0, n_mels=128, fmin=0.0, fmax=None, htk=False, norm='slaney')

Onset strength envelope of every channel.

The envelope is the aggregated positive increase of the log-power mel spectrogram (power_to_db with ref=1, top_db=80) from frame t - lag to t.

Parameters:
  • lag (int) – Time lag of the difference in frames. Default 1.

  • max_size (int) – Maximum filter across frequency on the reference (SuperFlux); 1 disables it. Default 1.

  • detrend (bool) – High-pass filter the envelope. Default False.

  • center (bool) – Compensate the centred-STFT delay. Default True.

  • aggregate – Reduction across mel bins: None (mean), numpy.mean, numpy.median, numpy.max, numpy.min, numpy.sum, a name, or a callable f(x, axis=-1).

  • n_fft (int) – Default 2048.

  • hop_length (int) – Default 512.

  • win_length – Mel spectrogram parameters, as melspectrogram.

  • window – Mel spectrogram parameters, as melspectrogram.

  • pad_mode – Mel spectrogram parameters, as melspectrogram.

  • power – Mel spectrogram parameters, as melspectrogram.

  • n_mels – Mel spectrogram parameters, as melspectrogram.

  • fmin – Mel spectrogram parameters, as melspectrogram.

  • fmax – Mel spectrogram parameters, as melspectrogram.

  • htk – Mel spectrogram parameters, as melspectrogram.

  • norm – Mel spectrogram parameters, as melspectrogram.

Returns:

shape (channels, n_frames) with n_frames = 1 + len // hop_length; index [0] for the (n_frames,) envelope of mono audio.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

onset_strength_multi(*, channels=None, lag=1, max_size=1, detrend=False, center=True, aggregate=None, n_fft=2048, hop_length=512, win_length=None, window='hann', pad_mode='constant', power=2.0, n_mels=128, fmin=0.0, fmax=None, htk=False, norm='slaney')

Multi-band onset strength of every channel: one envelope per group of mel bands.

Parameters:
  • channels (Optional[Sequence[int] | Sequence[slice]]) – Sub-band boundaries in mel bins: values above n_mels are dropped, the rest sorted and de-duplicated, each consecutive pair is one band. Or one slice of the mel bins per band, in any order. None gives one band.

  • aggregate – As onset_strength; False keeps every mel bin.

  • **kwargs – lag, max_size, detrend, center, n_fft, hop_length, win_length, window, pad_mode, power, n_mels, fmin, fmax, htk, norm as onset_strength.

Returns:

shape (channels, n_bands, n_frames) (n_mels rows with aggregate=False); index [0] for the (n_bands, n_frames) array of mono audio.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters or boundaries.

pad(pad_start_seconds, pad_end_seconds, pad_value)

Pad the buffer with constant values on both sides.

Parameters:
  • pad_start_seconds (float) – Duration to pad before the signal.

  • pad_end_seconds (float) – Duration to pad after the signal.

  • pad_value (float) – Value used for padding.

Returns:

New buffer with the added padding.

Return type:

AudioSamples

Raises:

AudioError – If padding fails or durations are invalid.

pad_samples_right(target_num_samples, pad_value)

Right-pad the buffer to a fixed sample count.

Parameters:
  • target_num_samples (int) – Desired total number of samples.

  • pad_value (float) – Value used for padding.

Returns:

New buffer of target_num_samples samples. If the

buffer is already at least that long it is returned unchanged (not truncated, no error).

Return type:

AudioSamples

Raises:

AudioError – If padding fails.

pad_to_duration(target_duration_seconds, pad_value, pad_side)

Pad the buffer to reach a target duration.

Parameters:
  • target_duration_seconds (float) – Desired total duration.

  • pad_value (float) – Value used for padding.

  • pad_side (PadSide) – Side to apply the padding.

Returns:

New buffer matching the requested duration.

Return type:

AudioSamples

Raises:

AudioError – If padding fails or the target duration is invalid.

pan(pan_value)

Apply stereo panning to the buffer in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:

pan_value (float) – Normalized pan value; negative favors left, positive favors right.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If the pan adjustment fails.

parametric_eq(eq)

Apply a parametric equalizer configuration, returning a new buffer.

Non-mutating twin of apply_parametric_eq(); leaves the current buffer unchanged.

Parameters:

eq (ParametricEq) – Equalizer definition containing one or more bands.

Returns:

A new equalized buffer.

Return type:

AudioSamples

Raises:

AudioError – If filter application fails.

peak()

Compute the peak sample value across all channels.

Returns:

Maximum absolute amplitude present in the buffer.

Return type:

int | float

percussive(*, kernel_size=31, power=2.0, mask=False, margin=1.0, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

Percussive component from median-filtering harmonic/percussive separation.

Parameters:

harmonic. (As)

Returns:

the percussive component, same length.

Return type:

AudioSamples

percussive_in_place(*, kernel_size=31, power=2.0, mask=False, margin=1.0, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

In-place percussive; arguments as harmonic.

perturb(config)

Apply stochastic perturbations and return a new buffer.

Parameters:

config (PerturbationConfig) – Configuration describing perturbations to apply.

Returns:

Perturbed buffer.

Return type:

AudioSamples

Raises:

AudioError – If perturbation fails.

perturb_in_place(config)

Apply stochastic perturbations in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:

config (PerturbationConfig) – Configuration describing perturbations to apply.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If perturbation fails.

phase_deviation_matrix(config)

Compute the magnitude-weighted phase deviation matrix.

Entry [b, t] is |X[b,t]| * |princarg(phi[b,t] - 2 phi[b,t-1] + phi[b,t-2])|, the phase term of the complex-domain onset detection function: zero for any steady tone and for bins without signal. Columns 0 and 1 are zero.

Parameters:

config (ComplexOnsetConfig) – Parameters controlling magnitude and phase processing.

Returns:

Phase deviation matrix with axes (frequency_bins, frames).

Return type:

numpy.ndarray

Raises:

AudioError – If matrix computation fails.

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.

pitch_shift(n_steps, *, bins_per_octave=12, res_type='soxr_hq', scale=False, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

Shifts the pitch by n_steps without changing the duration.

Time-stretch by rate = 2 ** (-n_steps / bins_per_octave), resample by rate, then cut/pad to the original length.

Parameters:
  • n_steps (float) – Shift in steps (semitones by default); fractional and negative values allowed.

  • bins_per_octave (int) – Steps per octave. Default 12.

  • res_type (str | ResamplingQuality) – Quality of this library’s windowed-sinc resampler: "soxr_hq" (default) maps to ResamplingQuality.high, "soxr_mq" to medium and "soxr_lq" to fast.

  • scale (bool) – Must be False.

  • n_fft – STFT parameters of the time stretch.

  • hop_length – STFT parameters of the time stretch.

  • win_length – STFT parameters of the time stretch.

  • window – STFT parameters of the time stretch.

  • center – STFT parameters of the time stretch.

  • pad_mode – STFT parameters of the time stretch.

Returns:

the shifted audio, same length, type and rate.

Return type:

AudioSamples

Raises:

ValueError – For a non-finite n_steps, scale=True or invalid parameters.

pitch_shift_in_place(n_steps, *, bins_per_octave=12, res_type='soxr_hq', scale=False, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

In-place pitch_shift; arguments as pitch_shift.

plp(*, hop_length=512, win_length=384, tempo_min=30, tempo_max=300, prior=None)

Predominant local pulse of every channel.

Parameters:
  • hop_length (int) – Hop of the (median-aggregated) onset envelope. Default 512.

  • win_length (int) – Fourier tempogram window in frames. Default 384.

  • tempo_min (Optional[float]) – Lowest tempo (BPM). Default 30.

  • tempo_max (Optional[float]) – Highest tempo (BPM). Default 300.

  • prior – Tempo prior (see tempo).

Returns:

shape (channels, n_frames), values in [0, 1]; index [0] for the (n_frames,) array of mono audio.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – If tempo_max <= tempo_min or parameters are invalid.

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.

power_spectral_density(window_size=2048, overlap=0.5)

Estimate the power spectral density across overlapping windows.

Parameters:
  • window_size (int) – STFT window length in samples; must be greater than zero.

  • overlap (float) – Fractional overlap between successive windows.

Returns:

Power spectral density carrying both the frequency axis and the

power-per-Hz density, averaged over time.

Return type:

Psd

Raises:
  • ValueError – If window_size is zero.

  • AudioError – If the PSD computation fails.

preemphasis(*, coef=0.97)

Pre-emphasis y[n] = x[n] - coef * x[n - 1] of every channel, with initial state 2 x[0] - x[1]. Use audio_samples.effects.preemphasis for zi / return_zf.

Parameters:

coef (float) – Coefficient. Default 0.97.

Returns:

the filtered audio.

Return type:

AudioSamples

Raises:

ValueError – For a non-finite coef or fewer than two samples.

preemphasis_in_place(*, coef=0.97)

In-place preemphasis.

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.

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.

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.

remix(intervals, *, align_zeros=False)

Concatenates sample intervals in the given order.

Parameters:
  • intervals (array_like) – (n, 2) [start, end) sample ranges, in output order; clipped to the signal, empty ranges skipped.

  • align_zeros (bool) – Snap boundaries to the nearest zero crossing of the (mono downmix of the) signal. Default False.

Returns:

the remixed audio.

Return type:

AudioSamples

Raises:

ValueError – For malformed or all-empty intervals.

remix_in_place(intervals, *, align_zeros=False)

In-place remix.

remove_dc_offset()

Remove the DC offset from the signal in-place.

Modifies the signal in place and returns None (the NumPy array it was created from, if any, is left unchanged).

Raises:

AudioError – If offset removal fails.

repeat(count)

Repeat the buffer a fixed number of times.

Parameters:

count (int) – Number of repetitions; must be greater than zero.

Returns:

Concatenated buffer containing the repeated audio.

Return type:

AudioSamples

Raises:

AudioError – If repetition fails.

resample(target_sample_rate, quality='fast')

Resample the audio to a new sample rate.

A Kaiser-windowed sinc interpolator evaluated at the exact rational position of every output sample: the output is time-aligned with the input (no filter delay, nothing to trim), the signal is treated as zero outside its ends (so the tail is flushed), and the result has exactly ceil(n * target_sample_rate / sample_rate) samples per channel. The cut-off sits just below the Nyquist frequency of the lower rate, so downsampling is anti-aliased and upsampling anti-imaged. Processing is in the sample type’s float (float32 for uint8, int16, int24 and float32; float64 for int32 and float64); the result keeps the input’s sample type.

Quality tiers (Nyquist of the lower rate):

  • "fast" (default): downsampling with a short windowed sinc (passband 0.80 x Nyquist, 70 dB stopband); upsampling by linear interpolation (images are not suppressed).

  • "medium": passband 0.90 x Nyquist, 100 dB stopband.

  • "high": passband 0.913 x Nyquist, 125 dB stopband.

  • "very_high": 185 dB stopband; passband 0.95 x Nyquist for decimation by a power of two, 0.98 for other ratios with no prime factor above 7, 0.996 for the rest (such as pitch shifts).

Parameters:
  • target_sample_rate (int) – Output sample rate in Hz (> 0).

  • quality (ResamplingQuality | str) – ResamplingQuality.fast (default), .medium, .high, .very_high, or the names "fast", "medium", "high", "very_high".

Returns:

the resampled audio (a copy when the rates are equal).

Return type:

AudioSamples

Raises:

ValueError – If target_sample_rate is not a positive integer, or an unknown quality name is given.

resample_by_ratio(ratio, quality='fast')

Resample the audio by a ratio of sample rates.

The target rate is round(sample_rate * ratio); the conversion is then exactly resample(target_rate, quality) (delay-free, exactly ceil(n * target_rate / sample_rate) samples; see resample for the quality tiers).

Parameters:
Returns:

the resampled audio at round(sample_rate * ratio) Hz.

Return type:

AudioSamples

Raises:

ValueError – If ratio is not positive or the target rate rounds to 0.

reverse()

Reverse the samples and return a new buffer.

Returns:

Buffer containing the reversed samples.

Return type:

AudioSamples

reverse_in_place()

Reverse the samples in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If reversal fails.

rfft(n_fft)

Compute the magnitude of the one-sided FFT.

Equal to numpy.abs(numpy.fft.rfft(x, n_fft)) per channel: real magnitudes of the n_fft // 2 + 1 non-negative frequency bins (use fft() for the complex values).

Parameters:

n_fft (int) – FFT size in samples; must be greater than zero.

Returns:

Magnitude spectrum shaped (channels, n_fft // 2 + 1).

Return type:

numpy.ndarray

Raises:
  • ValueError – If n_fft is zero.

  • AudioError – If the RFFT computation fails.

rms()

Compute the root mean square (RMS) energy of the samples.

Returns:

RMS amplitude across all samples and channels.

Return type:

float

rms_and_peak()

Compute the RMS and peak absolute value in a single pass.

Equivalent to calling rms and peak separately, but reads the sample buffer only once.

Returns:

A (rms, peak) pair where rms is the

root-mean-square as a float and peak is the maximum absolute sample value in the native sample type.

Return type:

tuple[float, int | float]

rms_envelope(window_size, hop_size)

Compute a root-mean-square envelope over sliding windows.

Parameters:
  • window_size (int) – Analysis window size in samples; must be greater than zero.

  • hop_size (int) – Step between windows in samples; must be greater than zero.

Returns:

RMS envelope shaped (channels, frames).

Return type:

numpy.ndarray

Raises:
  • ValueError – If window_size or hop_size is zero.

  • AudioError – If envelope computation fails.

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.

sample_rate

Sample rate in Hz.

Returns:

Sample rate (e.g., 44100, 48000, 96000).

Return type:

int

Examples

>>> audio.sample_rate
44100
samples_per_channel()

Number of samples per channel.

For multi-channel audio, this is the length of each channel. For mono audio, this equals the total number of samples.

Returns:

Number of samples in each channel.

Return type:

int

Examples

>>> stereo = aus.AudioSamples.from_array(np.zeros((2, 44100)), 44100)
>>> stereo.samples_per_channel()
44100
scale(factor)

Scale samples by a constant factor in-place.

Modifies the signal in place and returns None (the NumPy array it was created from, if any, is left unchanged).

Parameters:

factor (float) – Multiplier applied to every sample; values above 1.0 amplify and below 1.0 attenuate.

shape

Shape of the audio data.

Returns:

Shape as [samples] for mono or [channels, samples] for multi-channel.

Return type:

list[int]

Examples

>>> mono.shape
[44100]
>>> stereo.shape
[2, 44100]
size

Total number of samples across all channels (NumPy-style alias of len).

spectral_bandwidth(reduction=Ellipsis)

Compute the spectral bandwidth (spectral spread) of the signal.

The magnitude-weighted standard deviation of the spectrum about its spectral centroid. Larger values indicate energy spread across a wider frequency range; a pure tone yields a value near zero.

Parameters:

reduction (ChannelReduction) – Channel-reduction policy applied to multi-channel input. Defaults to ChannelReduction.average.

Returns:

Spectral bandwidth in Hz. Returns 0.0 for silence.

Return type:

float

Raises:

AudioError – If the FFT computation fails or the reduction is invalid for the channel layout.

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.

spectral_centroid(reduction=Ellipsis)

Compute the spectral centroid of the whole signal.

Parameters:

reduction (ChannelReduction) – Channel-reduction policy applied to multi-channel input. Defaults to ChannelReduction.average.

Returns:

Centroid in Hz of the power spectrum |X|**2 of the whole

signal (a single FFT, not frame-wise). Returns 0.0 for silence.

Return type:

float

Raises:

AudioError – If the FFT computation fails or the reduction is invalid for the channel layout.

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.

spectral_contrast(n_bands, reduction=Ellipsis)

Compute spectral contrast across octave-spaced sub-bands.

The spectrum is partitioned into n_bands octave-spaced sub-bands. Within each band the contrast is the dB difference between the mean of the top quantile (peaks) and the mean of the bottom quantile (valleys). High contrast indicates clear tonal/harmonic structure.

Parameters:
  • n_bands (int) – Number of octave-spaced sub-bands; must be greater than zero.

  • reduction (ChannelReduction) – Channel-reduction policy applied to multi-channel input. Defaults to ChannelReduction.average.

Returns:

n_bands contrast values in dB, low band to high band.

Return type:

list[float]

Raises:
  • ValueError – If n_bands is zero.

  • AudioError – If the FFT computation fails or the reduction is invalid for the channel layout.

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).

spectral_crest(reduction=Ellipsis)

Compute the spectral crest factor of the signal.

The ratio of the peak magnitude to the mean magnitude of the spectrum. High values indicate a strongly peaked (tonal) spectrum; a flat spectrum approaches 1.

Parameters:

reduction (ChannelReduction) – Channel-reduction policy applied to multi-channel input. Defaults to ChannelReduction.average.

Returns:

Spectral crest factor (>= 1 for non-silent signals). Returns

0.0 for silence.

Return type:

float

Raises:

AudioError – If the FFT computation fails or the reduction is invalid for the channel layout.

spectral_flatness(reduction=Ellipsis)

Compute the spectral flatness (Wiener entropy) of the signal.

The ratio of the geometric mean to the arithmetic mean of the power spectrum. Values near 1 indicate noise-like (flat) spectra, while values near 0 indicate tonal spectra dominated by a few peaks.

Parameters:

reduction (ChannelReduction) – Channel-reduction policy applied to multi-channel input. Defaults to ChannelReduction.average.

Returns:

Spectral flatness in [0, 1]. Returns 0.0 for silence.

Return type:

float

Raises:

AudioError – If the FFT computation fails or the reduction is invalid for the channel layout.

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.

spectral_flux(cqt_params, window_size, hop_size, method)

Compute spectral flux values without peak picking.

Parameters:
  • cqt_params (CqtParams) – Parameters controlling the constant-Q transform.

  • window_size (int) – Frame size in samples; must be greater than zero.

  • hop_size (int) – Hop size in samples; must be greater than zero.

  • method (SpectralFluxMethod) – Flux computation strategy.

Returns:

(times, flux): the frame times in

seconds first, then the flux values (one per frame).

Return type:

tuple[list[float], list[float]]

Raises:
  • ValueError – If window_size or hop_size is zero.

  • AudioError – If flux computation fails.

spectral_rolloff(rolloff_percent=0.85, reduction=Ellipsis)

Compute the spectral rolloff point for the provided energy fraction.

Parameters:
  • rolloff_percent (float) – Target cumulative spectral energy fraction between 0 and 1.

  • reduction (ChannelReduction) – Channel-reduction policy applied to multi-channel input. Defaults to ChannelReduction.average.

Returns:

Frequency where the cumulative spectrum reaches the rolloff threshold.

Return type:

float

Raises:

AudioError – If the FFT computation fails or rolloff_percent is invalid.

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.

spectral_slope(reduction=Ellipsis)

Compute the spectral slope of the signal.

The slope of an ordinary least-squares linear fit of the linear magnitude spectrum against frequency (Hz), in units of magnitude per Hz. A negative slope indicates energy concentrated at low frequencies.

Parameters:

reduction (ChannelReduction) – Channel-reduction policy applied to multi-channel input. Defaults to ChannelReduction.average.

Returns:

Least-squares slope (magnitude per Hz). Returns 0.0 for

silence or a degenerate single-bin spectrum.

Return type:

float

Raises:

AudioError – If the FFT computation fails or the reduction is invalid for the channel layout.

spectrogram_matrix(*, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant', power=1.0)

Magnitude spectrogram |STFT| ** power of every channel.

Equivalent to numpy.abs(self.stft_matrix(...)) ** power.

Parameters:
  • n_fft – As stft_matrix.

  • hop_length – As stft_matrix.

  • win_length – As stft_matrix.

  • window – As stft_matrix.

  • center – As stft_matrix.

  • pad_mode – As stft_matrix.

  • power (float) – Exponent; 1.0 (default) gives magnitude, 2.0 power.

Returns:

shape (channels, 1 + n_fft // 2, n_frames); float32 for uint8, int16, int24 and float32 audio, float64 for int32 and float64 audio.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters or a non-positive power.

speech_regions(config)

Compute contiguous speech regions as (start_sample, end_sample) pairs.

Parameters:

config (VadConfig) – Parameters controlling the voice activity detector.

Returns:

Regions marked as speech with sample-based start and exclusive end.

Return type:

list[tuple[int, int]]

Raises:

AudioError – If region extraction fails.

split(segment_duration_seconds)

Split the buffer into equal-length segments.

Parameters:

segment_duration_seconds (float) – Duration of each segment.

Returns:

List of segments that cover the original buffer.

Return type:

list[AudioSamples]

Raises:

AudioError – If segmentation fails or the duration is invalid.

split_db(*, top_db, ref='max', frame_length=2048, hop_length=512, aggregate=None)

Non-silent intervals: frames within top_db of the reference.

Parameters:
  • top_db – As trim_db.

  • ref – As trim_db.

  • frame_length – As trim_db.

  • hop_length – As trim_db.

  • aggregate – As trim_db.

Returns:

shape (n_intervals, 2) of [start, end) sample ranges ((0, 2) if everything is silent).

Return type:

numpy.ndarray[int64]

classmethod stack(sources)

Stack multiple buffers along the channel axis.

Parameters:

sources (list[AudioSamples]) – Buffers to stack; must share dtype and sample rate.

Returns:

Combined buffer with channels from each source.

Return type:

AudioSamples

Raises:

AudioError – If stacking fails or sources are incompatible.

std_dev()

Compute the standard deviation of the sample values.

Returns:

Standard deviation derived from the variance.

Return type:

float

stft(params)

Compute the Short-Time Fourier Transform (STFT).

Parameters:

params (StftParams) – Configuration controlling window length, hop size, and window type.

Returns:

Object containing complex spectrum, frequency bins, and time stamps.

Return type:

StftResult

Raises:

AudioError – If the STFT computation fails.

stft_matrix(*, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

Complex short-time Fourier transform of every channel.

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

  • hop_length (Optional[int]) – Samples between frames. None means win_length // 4.

  • win_length (Optional[int]) – Window length (<= n_fft); None means n_fft. Shorter windows are zero-padded to n_fft.

  • window (str | tuple | numpy.ndarray) – Window specification, as scipy.signal.get_window: "hann" (default), "hamming", "blackman", "blackmanharris", "boxcar"/"rectangular", "bartlett", "triang", ("kaiser", beta), ("gaussian", std), or an array of win_length coefficients. Named windows are periodic (fftbins=True).

  • center (bool) – Pad by n_fft // 2 on both sides so frame t is centred on sample t * hop_length. Default True.

  • pad_mode (str) – "constant" (zeros, default), "reflect", "edge" or "symmetric".

Returns:

shape (channels, 1 + n_fft // 2, n_frames); complex64 for uint8, int16, int24 and float32 audio, complex128 for int32 and float64 audio. Mono audio gives a leading axis of length 1 (index [0] for (1 + n_fft // 2, n_frames)).

Return type:

numpy.ndarray[complex64 | complex128]

Raises:

ValueError – For invalid parameters, or center=False with a signal shorter than n_fft.

sub_numpy_array(numpy_array)
swap_channels(channel1, channel2)

Swap two channels in place.

Modifies the signal in place and returns None. If the AudioSamples was created from a NumPy array (new_mono/new_multi), that array is modified too; pass arr.copy() to keep the original.

Parameters:
  • channel1 (int) – Zero-based index of the first channel.

  • channel2 (int) – Zero-based index of the second channel.

Returns:

Operation mutates the current buffer.

Return type:

None

Raises:

AudioError – If swapping fails or indices are invalid.

tempo(*, hop_length=512, start_bpm=120, std_bpm=1.0, ac_size=8.0, max_tempo=320.0, aggregate='mean', prior=None)

Estimates the tempo of every channel in BPM.

Parameters:
  • hop_length (int) – Hop of the onset envelope. Default 512.

  • start_bpm (float) – Prior centre. Default 120.

  • std_bpm (float) – Prior spread in octaves. Default 1.

  • ac_size (float) – Autocorrelation window in seconds. Default 8.

  • max_tempo (Optional[float]) – Exclude tempi at or above this. Default 320.

  • aggregate – Reduction over time (default numpy.mean); None gives one tempo per frame.

  • prior – None (log-normal), a scipy.stats distribution or a callable of the BPM returning a log-density.

Returns:

shape (channels, 1) ((channels, n_frames) with aggregate=None); index [0] for the (1,) array of mono audio.

Return type:

numpy.ndarray[float64]

Raises:

ValueError – For invalid parameters.

tempogram(*, hop_length=512, win_length=384, center=True, window='hann', norm=inf)

Autocorrelation tempogram of every channel.

Parameters:
  • hop_length (int) – Hop of the onset envelope. Default 512.

  • win_length (int) – Autocorrelation window (lag bins). Default 384.

  • center (bool) – Centre the windows. Default True.

  • window – Window before the autocorrelation. Default "hann".

  • norm (Optional[float]) – Column normalisation (numpy.inf default, a p-norm, or None).

Returns:

shape (channels, win_length, n_frames); index [0] for the 2-D array of mono audio.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – For invalid parameters.

tempogram_ratio(*, hop_length=512, win_length=384, start_bpm=120, std_bpm=1.0, max_tempo=320.0, factors=None, aggregate=None, prior=None, center=True, window='hann', fill_value=0, norm=inf)

Tempogram ratio features of every channel: the tempogram sampled at fixed multiples of the per-frame tempo estimate.

Parameters:
  • hop_length (int) – Hop of the onset envelope. Default 512.

  • win_length – Tempogram parameters (as tempogram).

  • center – Tempogram parameters (as tempogram).

  • window – Tempogram parameters (as tempogram).

  • norm – Tempogram parameters (as tempogram).

  • start_bpm – Per-frame tempo estimation (as tempo).

  • std_bpm – Per-frame tempo estimation (as tempo).

  • max_tempo – Per-frame tempo estimation (as tempo).

  • prior – Per-frame tempo estimation (as tempo).

  • factors (Optional[array_like]) – Tempo multiples; None uses the 13 default factors.

  • aggregate – Optional reduction over time (default None).

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

Returns:

shape (channels, n_factors, n_frames), or (channels, n_factors, 1) when aggregated (the time axis is kept); index [0] for the array of mono audio.

Return type:

numpy.ndarray[float32 | float64]

time_axis()

Time of each sample in seconds, one value per sample of a channel: numpy.arange(samples_per_channel()) / sample_rate.

time_stretch(rate, *, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

Changes the speed without changing the pitch.

STFT, phase_vocoder by rate, inverse STFT to exactly round(n / rate) samples.

Parameters:
  • rate (float) – Speed-up factor (2.0 = twice as fast, half the length).

  • n_fft – STFT parameters, as stft_matrix.

  • hop_length – STFT parameters, as stft_matrix.

  • win_length – STFT parameters, as stft_matrix.

  • window – STFT parameters, as stft_matrix.

  • center – STFT parameters, as stft_matrix.

  • pad_mode – STFT parameters, as stft_matrix.

Returns:

the stretched audio (input sample type and rate).

Return type:

AudioSamples

Raises:

ValueError – If rate is not positive, the result would be empty, or STFT parameters are invalid.

time_stretch_in_place(rate, *, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='constant')

In-place time_stretch (the length changes); arguments as time_stretch.

to_format(dtype)

Convert to another sample type with audio-aware scaling.

Audio-aware conversion: values are rescaled between the formats’ full-scale ranges, so a float 1.0 and an int16 32767 both mean full scale. Integer scaling is asymmetric because two’s-complement ranges are: float -1.0 maps to -32768 and +1.0 to 32767 (int16; likewise for int24/int32), i.e. negative values scale by 2**(bits-1) and positive values by 2**(bits-1) - 1, with rounding and saturation at the integer limits. uint8 is offset binary (-1.0 -> 0, 0.0 -> 128, 1.0 -> 255). Float-to-float conversions do not clip. Compare cast_as(), which keeps the numeric value instead.

Parameters:

dtype (SampleType) – Target type, e.g. SampleType.I16.

Returns:

New buffer of the target type.

Return type:

AudioSamples

Examples

>>> import numpy as np, audio_samples as aus
>>> x = aus.AudioSamples.new_mono(np.array([-1.0, -0.5, 0.0, 0.5, 1.0]), sample_rate=8000)
>>> x.to_format(aus.SampleType.I16).to_numpy()
array([-32768, -16384,      0,  16384,  32767], dtype=int16)
to_gpu_tensor(gpu_id=None)

Convert AudioSamples to a PyTorch tensor on the GPU if possible

to_mono(method=Ellipsis)

Convert the audio buffer to mono using the provided strategy.

Parameters:

method (MonoConversionMethod) – Conversion method describing how to combine channels.

Returns:

New buffer with a single channel.

Return type:

AudioSamples

Raises:

AudioError – If channel conversion fails.

to_numpy()

Convert audio samples to a NumPy array.

Returns the audio data as a numpy.ndarray. If the audio is already backed by a numpy array, returns the existing array (zero-copy). Otherwise, creates a new numpy array from the owned data.

Returns:

Audio data with shape:
  • (samples,) for mono audio

  • (channels, samples) for multi-channel audio

Return type:

numpy.ndarray

Examples

>>> audio = aus.AudioSamples.from_array(np.random.randn(2, 44100), 44100)
>>> arr = audio.to_numpy()
>>> arr.shape
(2, 44100)
>>> arr.dtype
dtype('float64')
to_stereo(method=Ellipsis)

Convert the audio buffer to stereo using the provided strategy.

Parameters:

method (StereoConversionMethod) – Conversion method describing how to expand channels.

Returns:

New buffer with two channels.

Return type:

AudioSamples

Raises:

AudioError – If channel conversion fails.

to_tensor(device)

Convert AudioSamples to a PyTorch tensor

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.

total_samples

Total number of samples across all channels.

Returns:

Total samples = num_channels x samples_per_channel.

Return type:

int

Examples

>>> stereo.total_samples  # 2 channels x 44100 samples
88200
track_pitch(window_size, hop_size, pitch_method=Ellipsis, threshold=0.1, min_frequency=50.0, max_frequency=2000.0)

Track the detected pitch over successive analysis windows.

Parameters:
  • window_size (int) – Size of each analysis window in samples; must be greater than zero.

  • hop_size (int) – Step between windows in samples; must be greater than zero.

  • pitch_method (PitchDetectionMethod) – Detection strategy to apply per window. Only yin and autocorrelation are implemented; cepstrum and harmonic_product raise AudioParameterError.

  • threshold (float) – YIN threshold on d’(tau) in [0, 1]; lower is stricter (more unvoiced frames). Ignored for autocorrelation.

  • min_frequency (float) – Minimum expected frequency in hertz.

  • max_frequency (float) – Maximum expected frequency in hertz.

Returns:

Time-ordered pitch track of per-window frames.

Return type:

PitchContour

Raises:
  • ValueError – If window_size or hop_size is zero.

  • AudioError – If pitch tracking fails.

trim(start_seconds, end_seconds)

Trim the buffer to the given time range.

Parameters:
  • start_seconds (float) – Inclusive start offset in seconds.

  • end_seconds (float) – Exclusive end offset in seconds.

Returns:

Buffer containing only the requested region.

Return type:

AudioSamples

Raises:

AudioError – If the range is invalid or trimming fails.

trim_all_silence(threshold_db, min_silence_duration_seconds)

Remove every silent region longer than a minimum duration.

Unlike trim_silence(), which only trims leading and trailing silence, this removes interior silence runs as well. A region is treated as silent when its level stays below threshold_db for at least min_silence_duration_seconds.

Parameters:
  • threshold_db (float) – Silence threshold in decibels.

  • min_silence_duration_seconds (float) – Minimum duration, in seconds, a silent run must reach before it is removed.

Returns:

Buffer with qualifying silence removed.

Return type:

AudioSamples

Raises:

AudioError – If trimming fails.

trim_db(*, top_db, ref='max', frame_length=2048, hop_length=512, aggregate=None)

Trims leading and trailing silence.

A frame is non-silent when its RMS level (centred frames, dB relative to ref) is above -top_db; the kept region runs from the first non-silent frame to the end of the last. Not to be confused with trim_silence (sample-wise absolute dBFS threshold).

Parameters:
  • top_db (float) – Threshold below the reference in dB. Required.

  • ref (float | "max" | numpy.max) – Reference RMS amplitude; the default numpy.max uses the loudest frame.

  • frame_length (int) – RMS frame length. Default 2048.

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

  • aggregate – Channel combination: numpy.max (default), numpy.min, numpy.mean or any callable, called as aggregate(db, 0) on the (channels, frames) levels in dB of multichannel audio. A callable here or in ref runs with the GIL held.

Returns:

(trimmed, index): the trimmed AudioSamples and an int64 array [start, end] of the kept sample range.

Return type:

tuple

Raises:

ValueError – For invalid parameters, or if everything is silent (an AudioSamples cannot be empty; use split_db to test).

trim_db_in_place(*, top_db, ref='max', frame_length=2048, hop_length=512, aggregate=None)

In-place trim_db; returns the kept [start, end] (int64 array).

trim_silence(threshold_db)

Trim leading and trailing silence below a threshold.

Parameters:

threshold_db (float) – Silence threshold in decibels.

Returns:

Buffer with silence removed.

Return type:

AudioSamples

Raises:

AudioError – If trimming fails.

static uniform_mono(length, sample_rate, value)
static uniform_mono_f64(length, sample_rate, value)
static uniform_mono_i16(length, sample_rate, value)
static uniform_mono_i32(length, sample_rate, value)
static uniform_multi(channels, length, sample_rate, value)
static uniform_multi_f64(channels, length, sample_rate, value)
static uniform_multi_i16(channels, length, sample_rate, value)
static uniform_multi_i32(channels, length, sample_rate, value)
variance()

Compute the variance of the sample values.

Returns:

Variance of amplitudes across all samples and channels.

Return type:

float

voice_activity_mask(config)

Compute a per-frame voice activity mask.

Parameters:

config (VadConfig) – Parameters controlling the voice activity detector.

Returns:

Boolean mask where True marks frames with speech activity.

Return type:

list[bool]

Raises:

AudioError – If mask computation fails.

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".

windows(window_size, hop_size)

Split the signal into fixed-size, optionally overlapping windows.

Each window covers window_size samples per channel and successive windows start hop_size samples apart, so windows overlap when hop_size < window_size. Trailing data that does not fill a complete window is zero-padded (the crate’s default PaddingMode.Zero).

Note

The crate’s zero-copy windows_ref iterator yields views that borrow into the buffer and cannot be exposed to Python safely. This method therefore copies each window into a new NumPy array.

Parameters:
  • window_size (int) – Samples per channel in each window; must be > 0.

  • hop_size (int) – Samples between successive window starts; must be > 0.

Returns:

One array per window, each shaped (samples,)

for mono audio or (channels, samples) for multi-channel audio.

Return type:

list[numpy.ndarray]

Raises:

ValueError – If window_size or hop_size is zero.

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.

zero_crossing_rate()

Calculate the zero-crossing rate of the signal, in crossings per second.

zero_crossing_rate = zero_crossings() / (channels * duration_seconds), where duration_seconds = samples_per_channel / sample_rate: for multi-channel audio it is the mean of the per-channel rates. A pure sine of frequency f gives about 2 * f.

This is one global value in crossings per second; divide by sample_rate for crossings per sample. For the per-frame fraction of sign changes use zero_crossing_rate_frames.

Returns:

Zero crossings per second (crossings / duration),

averaged over channels.

Return type:

float

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.

zero_crossings()

Count the number of zero crossings in the signal.

A crossing is counted between consecutive samples x[n-1] and x[n] when one is > 0 and the other is <= 0 (zero counts as non-positive). For multi-channel audio the per-channel counts are summed.

Returns:

Number of crossings (summed over channels).

Return type:

int

static zeros_mono(length, sample_rate)
static zeros_mono_f64(length, sample_rate)
static zeros_mono_i16(length, sample_rate)
static zeros_mono_i32(length, sample_rate)
static zeros_multi(channels, length, sample_rate)
static zeros_multi_f64(channels, length, sample_rate)
static zeros_multi_i16(channels, length, sample_rate)
static zeros_multi_i32(channels, length, sample_rate)