Types

Types module for audio processing configurations and enumerations.

Configuration and result classes of the AudioSamples methods. Every class is also available from the top-level package.

class audio_samples.types.AdaptiveThresholdConfig(method, *, delta, percentile, window_size, min_threshold, max_threshold)

Bases: object

Configuration for adaptive thresholding in peak picking.

Adaptive thresholding dynamically adjusts the detection threshold based on local characteristics of the onset strength function to improve detection accuracy across varying signal conditions.

classmethod combined(delta, percentile, window_size)

Create a combined adaptive threshold configuration.

Parameters:
  • delta (float) – Delta offset for thresholding.

  • percentile (float) – Percentile value for thresholding.

  • window_size (int) – Size of the rolling window in frames.

Returns:

A new combined adaptive threshold configuration.

Return type:

AdaptiveThresholdConfig

static default()
classmethod delta(delta, window_size)

Create a delta-based adaptive threshold configuration.

Parameters:
  • delta (float) – Delta offset for thresholding.

  • window_size (int) – Size of the rolling window in frames.

Returns:

A new delta-based adaptive threshold configuration.

Return type:

AdaptiveThresholdConfig

max_threshold

Maximum allowable threshold.

min_threshold

Minimum allowable threshold.

classmethod percentile(percentile, window_size)

Create a percentile-based adaptive threshold configuration.

Parameters:
  • percentile (float) – Percentile value for thresholding.

  • window_size (int) – Size of the rolling window in frames.

Returns:

A new percentile-based adaptive threshold configuration.

Return type:

AdaptiveThresholdConfig

validate()

Validate the configuration parameters.

Raises an error if any parameters are invalid.

class audio_samples.types.AdaptiveThresholdMethod

Bases: object

Adaptive thresholding strategy for peak picking.

AdaptiveThresholdMethod selects how dynamic detection thresholds are estimated from the onset strength function over time when performing peak picking or onset detection.

Different strategies trade off responsiveness to rapid changes against robustness to noise and transient outliers.

Instances of AdaptiveThresholdMethod are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available methods:

  • AdaptiveThresholdMethod.delta

  • AdaptiveThresholdMethod.percentile

  • AdaptiveThresholdMethod.combined

combined = <audio_samples.types.AdaptiveThresholdMethod object>
static default()
delta = <audio_samples.types.AdaptiveThresholdMethod object>
percentile = <audio_samples.types.AdaptiveThresholdMethod object>
class audio_samples.types.BeatTrackingConfig(tempo_bpm, onset_config, tolerance=None)

Bases: object

Python wrapper for BeatTrackingConfig.

Configuration for beat detection.

onset_config

Get the onset detection config.

tempo_bpm

Get the tempo in BPM.

tolerance

Get the tolerance in seconds.

class audio_samples.types.BeatTrackingData(tempo_bpm, beat_times, config)

Bases: object

Python wrapper for BeatTrackingData.

Beat tracking results containing tempo and beat timestamps.

beat_times

Get the beat timestamps in seconds.

config

Get the configuration used.

tempo_bpm

Get the estimated tempo in BPM.

class audio_samples.types.ChannelReduction

Bases: object

Strategy for reducing a multi-channel signal to a single channel.

ChannelReduction controls how operations that fundamentally require a single channel (such as spectral centroid or roll-off) behave when presented with a multi-channel signal. It lets the caller choose between failing loudly, selecting a single channel, or averaging across channels.

Instances of ChannelReduction are immutable and should be treated as enum-like values. Zero-parameter strategies are accessed via class attributes, while the channel-selection strategy is constructed via a static method.

Available strategies:

  • ChannelReduction.error (default): Return an error when the signal has more than one channel.

  • ChannelReduction.first: Use the first channel (index 0) and ignore the rest.

  • ChannelReduction.average: Average the corresponding samples across all channels.

  • ChannelReduction.channel(index): Use the channel at the given (bounds-checked) index.

average = <audio_samples.types.ChannelReduction object>
static channel(index)

Use the channel at the given index.

The index is bounds-checked when the reduction is applied.

Parameters:

index (int) – Zero-based channel index to select.

static default()
error = <audio_samples.types.ChannelReduction object>
first = <audio_samples.types.ChannelReduction object>
class audio_samples.types.ComplexOnsetConfig(*, cqt_params, hop_size, window_size, peak_picking, magnitude_weight, phase_weight, magnitude_rectify, phase_rectify, log_compression)

Bases: object

Configuration for complex domain onset detection.

Complex domain onset detection uses both magnitude and phase information from the CQT to provide more accurate onset detection than magnitude-only methods, especially for polyphonic music and complex timbres.

cqt_params

Get the CQT parameters.

hop_size

Get the hop size in samples.

log_compression

Get the logarithmic compression factor.

magnitude_rectify

Get whether to rectify the magnitude component.

magnitude_weight

Get the magnitude weighting factor.

static musical(sample_rate)

Musical preset configuration.

Parameters:

sample_rate (int) – Sample rate of the audio the configuration will be applied to; the peak picker’s durations are converted to frames at sample_rate / hop_size.

peak_picking

Get the peak picking configuration.

Returns a copy: setting fields on the returned object does not change this config. Modify the copy and assign it back:

pp = config.peak_picking
pp.min_peak_separation = 256
config.peak_picking = pp
static percussive(sample_rate)

Percussive preset configuration.

Parameters:

sample_rate (int) – Sample rate of the audio the configuration will be applied to; the peak picker’s durations are converted to frames at sample_rate / hop_size.

phase_rectify

Get whether to rectify the phase component.

phase_weight

Get the phase weighting factor.

set_weights(magnitude_weight, phase_weight)

Set the magnitude and phase weighting factors.

static speech(sample_rate)

Speech preset configuration.

Parameters:

sample_rate (int) – Sample rate of the audio the configuration will be applied to; the peak picker’s durations are converted to frames at sample_rate / hop_size.

validate()

Validate the configuration parameters.

window_size

Get the window size in samples, or None if it defaults to CQT’s minimum window size.

class audio_samples.types.CompressorConfig(*, threshold_db, ratio, attack_ms, release_ms, makeup_gain_db, knee_type, knee_width_db, detection_method, side_chain, lookahead_ms)

Bases: object

Compressor configuration parameters.

CompressorConfig defines how a dynamic range compressor responds to signal levels above a threshold, including time constants, compression curve shape, detection method, and side-chain behaviour.

Instances of CompressorConfig are immutable value objects in the Python API. Parameters are provided at construction time and exposed via read-only properties internally. Validation can be performed explicitly using validate(sample_rate).

Several common presets are provided as class attributes, accessed without parentheses: CompressorConfig.vocal, CompressorConfig.drum, CompressorConfig.bus. (By contrast CompressorConfig.default() and the LimiterConfig presets such as LimiterConfig.mastering() are methods.) Parameters can be read back through read-only properties such as threshold_db and ratio.

attack_ms

Attack time in milliseconds.

bus = CompressorConfig { threshold_db: -20.0, ratio: 2.0, attack_ms: 10.0, release_ms: 200.0, makeup_gain_db: 1.0, knee_type: Soft, knee_width_db: 6.0, detection_method: Rms, side_chain: SideChainConfig { enabled: false, high_pass_freq: None, low_pass_freq: None, pre_emphasis_db: 0.0, external_mix: 1.0 }, lookahead_ms: 0.0 }
static default()
detection_method

Detection method driving gain reduction.

drum = CompressorConfig { threshold_db: -8.0, ratio: 6.0, attack_ms: 0.1, release_ms: 20.0, makeup_gain_db: 2.0, knee_type: Hard, knee_width_db: 0.5, detection_method: Peak, side_chain: SideChainConfig { enabled: false, high_pass_freq: None, low_pass_freq: None, pre_emphasis_db: 0.0, external_mix: 1.0 }, lookahead_ms: 0.0 }
explain(sample_rate=None, *, n_samples=None, n_channels=None, f0_range=None)

Explain what this compressor configuration will do.

Parameters:
  • sample_rate (float | None) – Sample rate in Hz of the signal it will be applied to. Without it, quantities that need a sample rate are omitted and an info warning says so.

  • n_samples (int | None) – Signal length in samples per channel.

  • n_channels (int | None) – Number of channels.

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

Returns:

The explanation (see audio_samples.explain).

Return type:

ExplainDoc

knee_type

Knee characteristic.

knee_width_db

Knee width in decibels.

lookahead_ms

Lookahead time in milliseconds.

makeup_gain_db

Makeup gain in decibels applied after compression.

ratio

Compression ratio (1.0 = no compression).

release_ms

Release time in milliseconds.

side_chain

Side-chain configuration.

threshold_db

Threshold level in decibels.

validate(sample_rate)

Validate compressor configuration parameters.

Parameters:

sample_rate (float) – Audio sample rate in Hz, used to validate time- and frequency-dependent constraints.

Returns:

The validated compressor configuration.

Return type:

CompressorConfig

Raises:

ValueError – If any configuration parameter is invalid.

vocal = CompressorConfig { threshold_db: -18.0, ratio: 3.0, attack_ms: 2.0, release_ms: 100.0, makeup_gain_db: 3.0, knee_type: Soft, knee_width_db: 4.0, detection_method: Rms, side_chain: SideChainConfig { enabled: false, high_pass_freq: None, low_pass_freq: None, pre_emphasis_db: 0.0, external_mix: 1.0 }, lookahead_ms: 0.0 }
class audio_samples.types.DynamicRangeMethod

Bases: object

Detection method for dynamic range processing.

DynamicRangeMethod selects how signal level is estimated when driving gain reduction in dynamics processors such as compressors, limiters, and gates.

Different methods trade off smoothness, transient responsiveness, and perceptual stability.

Instances of DynamicRangeMethod are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available detection methods:

  • DynamicRangeMethod.rms

  • DynamicRangeMethod.peak

  • DynamicRangeMethod.hybrid

static default()
hybrid = <audio_samples.types.DynamicRangeMethod object>
peak = <audio_samples.types.DynamicRangeMethod object>
rms = <audio_samples.types.DynamicRangeMethod object>
class audio_samples.types.EnvelopeFollower(attack_ms, release_ms, sample_rate, detection_method)

Bases: object

Python wrapper for EnvelopeFollower.

Envelope follower for attack/release envelope tracking.

classmethod default()

Create a default EnvelopeFollower with 10ms attack and 100ms release at 44100 Hz.

process(input)

Process one sample and return the current envelope level (>= 0).

The follower is stateful: successive calls continue from the previous envelope value. Call reset() to start again from 0.

Parameters:

input (float) – Input sample value (any numeric scale).

Returns:

Smoothed envelope level.

Return type:

float

process_array(samples)

Process a 1-D array sample by sample and return the envelope per sample.

Equivalent to np.array([follower.process(v) for v in samples]); the state carries over between calls.

Parameters:

samples (numpy.ndarray) – 1-D float64 array of input samples.

Returns:

Envelope level for each input sample.

Return type:

numpy.ndarray

reset()

Reset the envelope to 0 (and clear the RMS window).

class audio_samples.types.EqBand(band_type, frequency, gain_db, q_factor)

Bases: object

Parametric equaliser band configuration.

EqBand represents a single band in a parametric equaliser, defined by a band type, centre or cutoff frequency, gain, and quality factor (Q). Each band describes how a specific region of the frequency spectrum is shaped.

Instances of EqBand are immutable value objects. Parameters are provided at construction time and exposed via read-only properties.

Convenience constructors are available for common band types such as peak and shelving filters.

enabled

Whether this band is enabled.

explain(sample_rate=None, *, n_samples=None, n_channels=None, f0_range=None)

Explain what this EQ band will do.

Parameters:
  • sample_rate (float | None) – Sample rate in Hz of the signal it will be applied to. Without it, quantities that need a sample rate are omitted and an info warning says so.

  • n_samples (int | None) – Signal length in samples per channel.

  • n_channels (int | None) – Number of channels.

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

Returns:

The explanation (see audio_samples.explain).

Return type:

ExplainDoc

frequency

Centre or cutoff frequency in Hz.

gain_db

Gain in decibels.

classmethod high_shelf(frequency, gain_db, q_factor)

Create a high-shelf EQ band.

Parameters:
  • frequency (float) – Corner frequency in Hz.

  • gain_db (float) – Gain in decibels.

  • q_factor (float) – Shelf slope control.

classmethod low_shelf(frequency, gain_db, q_factor)

Create a low-shelf EQ band.

Parameters:
  • frequency (float) – Corner frequency in Hz.

  • gain_db (float) – Gain in decibels.

  • q_factor (float) – Shelf slope control.

classmethod peak(frequency, gain_db, q_factor)

Create a peaking (bell) EQ band.

Parameters:
  • frequency (float) – Centre frequency in Hz.

  • gain_db (float) – Gain in decibels. Positive values boost, negative values attenuate.

  • q_factor (float) – Quality factor controlling bandwidth.

q_factor

Quality factor controlling bandwidth or slope.

class audio_samples.types.EqBandType

Bases: object

Parametric equaliser band type.

EqBandType defines how gain is applied across the frequency spectrum relative to a centre or cutoff frequency. Different band types emphasise or suppress different spectral regions.

Instances of EqBandType are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available band types:

  • EqBandType.peak

  • EqBandType.low_shelf

  • EqBandType.high_shelf

  • EqBandType.low_pass

  • EqBandType.high_pass

  • EqBandType.band_pass

  • EqBandType.band_stop

band_pass = <audio_samples.types.EqBandType object>
band_stop = <audio_samples.types.EqBandType object>
static default()
high_pass = <audio_samples.types.EqBandType object>
high_shelf = <audio_samples.types.EqBandType object>
low_pass = <audio_samples.types.EqBandType object>
low_shelf = <audio_samples.types.EqBandType object>
peak = <audio_samples.types.EqBandType object>
class audio_samples.types.ExpanderConfig(*, threshold_db, ratio, attack_ms, release_ms)

Bases: object

Downward expander configuration parameters.

ExpanderConfig defines how a downward expander attenuates a signal that falls below a threshold, increasing the dynamic range of low-level material. RMS detection is always used for expansion.

Instances of ExpanderConfig are immutable value objects in the Python API. Parameters are provided at construction time and exposed via read-only properties. Validation can be performed explicitly using validate().

A gentle expansion preset is provided via ExpanderConfig.gentle.

attack_ms

Attack time in milliseconds.

static default()
gentle = ExpanderConfig { threshold_db: -50.0, ratio: 1.5, attack_ms: 5.0, release_ms: 200.0 }
ratio

Expansion ratio applied below the threshold.

release_ms

Release time in milliseconds.

threshold_db

Expansion threshold in dBFS.

validate()

Validate expander configuration parameters.

Returns:

The validated expander configuration.

Return type:

ExpanderConfig

Raises:

ValueError – If any configuration parameter is invalid.

class audio_samples.types.FadeCurve

Bases: object

Fade curve shape for envelope operations.

FadeCurve represents the shape of an amplitude envelope used when applying fades, ramps, or transitions to audio signals. Different curves produce different perceptual characteristics in how the signal level changes over time.

Instances of FadeCurve are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available fade curves:

  • FadeCurve.linear

  • FadeCurve.exponential

  • FadeCurve.logarithmic

  • FadeCurve.smooth_step

static default()
exponential = <audio_samples.types.FadeCurve object>
linear = <audio_samples.types.FadeCurve object>
logarithmic = <audio_samples.types.FadeCurve object>
smooth_step = <audio_samples.types.FadeCurve object>
class audio_samples.types.FilterResponse

Bases: object

Filter response characteristic.

FilterResponse defines the qualitative frequency response shape of a filter, such as whether it attenuates low frequencies, high frequencies, or a band of frequencies.

Instances of FilterResponse are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available responses:

  • FilterResponse.lowpass

  • FilterResponse.highpass

  • FilterResponse.bandpass

  • FilterResponse.bandstop

bandpass = <audio_samples.types.FilterResponse object>
bandstop = <audio_samples.types.FilterResponse object>
static default()
highpass = <audio_samples.types.FilterResponse object>
lowpass = <audio_samples.types.FilterResponse object>
class audio_samples.types.GateConfig(*, threshold_db, ratio, attack_ms, release_ms)

Bases: object

Noise gate configuration parameters.

GateConfig defines how a downward noise gate attenuates a signal that falls below a threshold, including the attenuation ratio and the attack and release envelope time constants.

Instances of GateConfig are immutable value objects in the Python API. Parameters are provided at construction time and exposed via read-only properties. Validation can be performed explicitly using validate().

A general-purpose noise-gating preset is provided via GateConfig.noise_gate.

attack_ms

Attack time in milliseconds.

static default()
noise_gate = GateConfig { threshold_db: -45.0, ratio: 20.0, attack_ms: 0.5, release_ms: 150.0 }
ratio

Attenuation ratio applied below the threshold.

release_ms

Release time in milliseconds.

threshold_db

Gate threshold in dBFS.

validate()

Validate gate configuration parameters.

Returns:

The validated gate configuration.

Return type:

GateConfig

Raises:

ValueError – If any configuration parameter is invalid.

class audio_samples.types.HpssConfig(*, stft_params=None, median_filter_harmonic=17, median_filter_percussive=17, mask_softness=0.3)

Bases: object

Configuration for Harmonic/Percussive Source Separation (HPSS).

HPSS separates audio into harmonic and percussive components using STFT magnitude median filtering. Harmonic components are enhanced by median filtering along the time axis, while percussive components are enhanced by median filtering along the frequency axis.

freq_resolution(sample_rate)

Calculate the frequency resolution in Hz.

harmonic = HpssConfig { stft_params: StftParams { n_fft: 4096, hop_size: 512, window: Hanning, centre: true }, median_filter_harmonic: 51, median_filter_percussive: 17, mask_softness: 0.1 }
musical = HpssConfig { stft_params: StftParams { n_fft: 2048, hop_size: 512, window: Hanning, centre: true }, median_filter_harmonic: 31, median_filter_percussive: 31, mask_softness: 0.5 }
num_freq_bins()

Calculate the number of frequency bins for this configuration.

percussive = HpssConfig { stft_params: StftParams { n_fft: 2048, hop_size: 256, window: Hanning, centre: true }, median_filter_harmonic: 17, median_filter_percussive: 51, mask_softness: 0.1 }
realtime = HpssConfig { stft_params: StftParams { n_fft: 1024, hop_size: 256, window: Hanning, centre: true }, median_filter_harmonic: 11, median_filter_percussive: 11, mask_softness: 0.3 }
set_filter_sizes(harmonic_size, percussive_size)

Set median filter sizes.

Parameters:
  • harmonic (int) – Harmonic filter size (odd numbers recommended)

  • percussive (int) – Percussive filter size (odd numbers recommended)

set_mask_softness(softness)

Set mask softness parameter.

Parameters:

softness (float) – Softness value (0.0 = hard mask, 1.0 = completely soft)

set_stft_params(n_fft, hop_size)

Set STFT parameters.

Parameters:
  • n_fft (int) – FFT size in samples (should be a power of 2)

  • hop_size (int) – Hop size in samples, at most n_fft (typically n_fft/4)

Raises:

ValueError – If either value is 0 or hop_size is larger than n_fft. The configuration is then unchanged.

time_resolution(sample_rate)

Calculate the time resolution in seconds.

class audio_samples.types.IirFilterDesign(filter_type, response, order, cutoff_frequency=None, low_frequency=None, high_frequency=None, passband_ripple=None, stopband_attenuation=None, bessel_norm=None)

Bases: object

IIR filter design parameters.

IirFilterDesign describes the parameters required to construct a digital infinite impulse response (IIR) filter, including the filter family, response type, order, and frequency specifications.

Instances of IirFilterDesign are immutable value objects. Fields are exposed via read-only properties.

A generic constructor is provided for manual configuration, and convenience constructors are available for common Butterworth designs.

classmethod bessel(response, order, cutoff_frequency, norm='mag')

Create a Bessel low-pass / high-pass design.

norm ("mag", "phase" or "delay") defaults to "mag": -3 dB at the cutoff.

classmethod bessel_band(response, order, low_frequency, high_frequency, norm='mag')

Create a Bessel band-pass / band-stop design; norm as for bessel.

bessel_norm

Bessel normalisation ("mag", "phase" or "delay").

classmethod butterworth_bandpass(order, low_frequency, high_frequency)

Create a Butterworth band-pass filter design.

Parameters:
  • order (int) – Filter order.

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

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

classmethod butterworth_bandstop(order, low_frequency, high_frequency)

Create a Butterworth band-stop filter design between low_frequency and high_frequency Hz.

classmethod butterworth_highpass(order, cutoff_frequency)

Create a Butterworth high-pass filter design.

Parameters:
  • order (int) – Filter order.

  • cutoff_frequency (float) – Cutoff frequency in Hz.

classmethod butterworth_lowpass(order, cutoff_frequency)

Create a Butterworth low-pass filter design.

Parameters:
  • order (int) – Filter order.

  • cutoff_frequency (float) – Cutoff frequency in Hz.

Returns:

  • IirFilterDesign – A new Butterworth low-pass filter design instance.

  • Errors

  • ——

  • If the order argument is less than or equal to zero

classmethod chebyshev_i(response, order, cutoff_frequency, passband_ripple)

Create a Chebyshev Type I low-pass / high-pass design.

The passband ripples between 0 and -passband_ripple dB.

classmethod chebyshev_i_band(response, order, low_frequency, high_frequency, passband_ripple)

Create a Chebyshev Type I band-pass / band-stop design.

The passband ripples between 0 and -passband_ripple dB.

classmethod chebyshev_ii(response, order, cutoff_frequency, stopband_attenuation)

Create a Chebyshev Type II low-pass / high-pass design.

The stopband is at least stopband_attenuation dB down; cutoff_frequency is the stopband edge.

classmethod chebyshev_ii_band(response, order, low_frequency, high_frequency, stopband_attenuation)

Create a Chebyshev Type II band-pass / band-stop design.

The stopband is at least stopband_attenuation dB down; the band edges are the stopband edges.

cutoff_frequency

Cutoff frequency in Hz for low-pass and high-pass filters.

classmethod elliptic(response, order, cutoff_frequency, passband_ripple, stopband_attenuation)

Create an elliptic (Cauer) low-pass / high-pass design.

passband_ripple dB of passband ripple and at least stopband_attenuation dB of stopband attenuation.

classmethod elliptic_band(response, order, low_frequency, high_frequency, passband_ripple, stopband_attenuation)

Create an elliptic (Cauer) band-pass / band-stop design.

passband_ripple dB of passband ripple and at least stopband_attenuation dB of stopband attenuation.

explain(sample_rate=None, *, n_samples=None, n_channels=None, f0_range=None)

Explain what this IIR filter design will do.

Parameters:
  • sample_rate (float | None) – Sample rate in Hz of the signal it will be applied to. Without it, quantities that need a sample rate are omitted and an info warning says so.

  • n_samples (int | None) – Signal length in samples per channel.

  • n_channels (int | None) – Number of channels.

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

Returns:

The explanation (see audio_samples.explain).

Return type:

ExplainDoc

filter_type

Filter family used for the design.

frequency_response(frequencies, sample_rate)

Evaluate the frequency response of the design.

Parameters:
  • frequencies (np.typing.NDArray[np.float64]) – Frequencies in hertz.

  • sample_rate (float) – Sample rate in hertz.

Returns:

Linear magnitude and phase (radians, wrapped to (-pi, pi]) of the cascaded sections at frequencies.

Return type:

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

Raises:

ValueError – If the design is invalid for sample_rate.

high_frequency

Upper cutoff frequency in Hz for band-pass and band-stop filters.

low_frequency

Lower cutoff frequency in Hz for band-pass and band-stop filters.

order

Filter order (number of poles).

passband_ripple

Passband ripple in dB, if applicable.

response

Frequency response shape of the filter.

sos(sample_rate)

Design the filter and return its second-order sections.

Returns a (n_sections, 6) float64 array with rows [b0, b1, b2, a0, a1, a2] and a0 == 1, usable directly with scipy.signal.sosfilt.

Parameters:

sample_rate (float) – Sample rate in hertz.

Raises:

ValueError – If the design is invalid for sample_rate.

stopband_attenuation

Stopband attenuation in dB, if applicable.

class audio_samples.types.IirFilterType

Bases: object

IIR filter family selection for digital signal processing.

IirFilterType selects the analogue prototype used when designing an infinite impulse response (IIR) digital filter. Different families trade off passband ripple, stopband attenuation, transition sharpness, and phase behaviour.

Instances of IirFilterType are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available filter types:

  • IirFilterType.butterworth

  • IirFilterType.chebyshev_type_i

  • IirFilterType.chebyshev_type_ii

  • IirFilterType.elliptic

  • IirFilterType.bessel

bessel = <audio_samples.types.IirFilterType object>
butterworth = <audio_samples.types.IirFilterType object>
chebyshev_type_i = <audio_samples.types.IirFilterType object>
chebyshev_type_ii = <audio_samples.types.IirFilterType object>
static default()
elliptic = <audio_samples.types.IirFilterType object>
class audio_samples.types.Key(tonic, mode, confidence)

Bases: object

A musical key estimate.

Key pairs a tonic pitch class with a mode (major or minor) and a confidence score describing how strongly the estimate matched the analysed signal.

Instances are typically produced by key estimation, but can also be constructed directly. Fields are exposed via read-only properties.

confidence

Match confidence in [0.0, 1.0].

mode

The mode (major or minor) of the key.

tonic

The tonic pitch class of the key.

class audio_samples.types.KneeType

Bases: object

Knee characteristic for dynamic range processing.

KneeType controls how smoothly gain reduction transitions as the signal crosses the threshold in dynamics processors such as compressors and limiters.

Instances of KneeType are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available knee types:

  • KneeType.hard

  • KneeType.soft

static default()
hard = <audio_samples.types.KneeType object>
soft = <audio_samples.types.KneeType object>
class audio_samples.types.LimiterConfig(*, ceiling_db, attack_ms, release_ms, knee_type, knee_width_db, detection_method, side_chain, lookahead_ms, isp_limiting)

Bases: object

Limiter configuration parameters.

LimiterConfig defines how a limiter prevents signal levels from exceeding a specified ceiling, including time constants, knee behaviour, detection method, side-chain configuration, and inter-sample peak (ISP) limiting.

Instances of LimiterConfig are immutable value objects in the Python API. Parameters are provided at construction time and exposed via read-only properties internally. Validation can be performed explicitly using validate(sample_rate).

Several common presets are provided as class methods (LimiterConfig.mastering()), unlike CompressorConfig’s presets, which are class attributes.

isp_limiting makes the peak detector read true (inter-sample) peaks, interpolated at 4x, instead of sample peaks.

attack_ms

Attack time in milliseconds.

classmethod broadcast()

Broadcast limiter preset.

Tuned for aggressive peak control and regulatory compliance.

ceiling_db

Ceiling level in decibels.

static default()
detection_method

Detection method used for limiting.

explain(sample_rate=None, *, n_samples=None, n_channels=None, f0_range=None)

Explain what this limiter configuration will do.

Parameters:
  • sample_rate (float | None) – Sample rate in Hz of the signal it will be applied to. Without it, quantities that need a sample rate are omitted and an info warning says so.

  • n_samples (int | None) – Signal length in samples per channel.

  • n_channels (int | None) – Number of channels.

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

Returns:

The explanation (see audio_samples.explain).

Return type:

ExplainDoc

isp_limiting

Whether inter-sample peak limiting was requested.

Whether the peak detector reads true (inter-sample) peaks, interpolated at 4x, instead of sample peaks.

knee_type

Knee characteristic.

knee_width_db

Knee width in decibels.

lookahead_ms

Lookahead time in milliseconds.

classmethod mastering()

Mastering limiter preset.

Tuned for loudness maximisation with controlled transparency.

release_ms

Release time in milliseconds.

side_chain

Side-chain configuration.

classmethod transparent()

Transparent limiter preset.

Tuned for minimal audible impact while preventing clipping.

validate(sample_rate)

Validate limiter configuration parameters.

Parameters:

sample_rate (float) – Audio sample rate in Hz, used to validate time- and frequency-dependent constraints.

Returns:

The validated limiter configuration.

Return type:

LimiterConfig

Raises:

ValueError – If any configuration parameter is invalid.

class audio_samples.types.Mode

Bases: object

The mode (tonality) of an estimated musical key.

Mode distinguishes between the major and minor tonalities of a key estimate.

Instances of Mode are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available modes:

  • Mode.major

  • Mode.minor

major = Mode(major)
minor = Mode(minor)
class audio_samples.types.MonoConversionMethod

Bases: object

Method for converting multi-channel audio to mono.

MonoConversionMethod represents a strategy for collapsing multi-channel audio (e.g. stereo or surround) into a single mono channel. Different methods trade off simplicity, spatial fidelity, and control over channel weighting.

Instances of MonoConversionMethod are immutable and should be treated as value objects constructed via class methods.

Available conversion methods:

  • MonoConversionMethod.average()

  • MonoConversionMethod.left()

  • MonoConversionMethod.right()

  • MonoConversionMethod.weighted(weights: list[float])

  • MonoConversionMethod.center()

average = <audio_samples.types.MonoConversionMethod object>
center = <audio_samples.types.MonoConversionMethod object>
static default()
left = <audio_samples.types.MonoConversionMethod object>
right = <audio_samples.types.MonoConversionMethod object>
classmethod weighted(weights)

Weighted average across channels.

Each channel is multiplied by a corresponding weight prior to summation.

Parameters:

weights (list[float]) – Per-channel weights. The length should match the number of input channels.

class audio_samples.types.NoiseColor

Bases: object

Noise colour classification for audio perturbation and synthesis.

NoiseColor classifies stochastic noise processes by their spectral energy distribution. Different noise colours influence perceived brightness, smoothness, and temporal correlation in audio synthesis and perturbation tasks.

Instances of NoiseColor are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available noise colours:

  • NoiseColor.white

  • NoiseColor.pink

  • NoiseColor.brown

brown = <audio_samples.types.NoiseColor object>
static default()
pink = <audio_samples.types.NoiseColor object>
white = <audio_samples.types.NoiseColor object>
class audio_samples.types.NormalizationMethod

Bases: object

Normalisation strategy for audio sample data.

NormalizationMethod represents a predefined method for rescaling or re-centring audio samples prior to further processing. Normalisation is commonly used to stabilise numerical behaviour, improve comparability between signals, or enforce amplitude constraints.

Instances of NormalizationMethod are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available normalisation methods:

  • NormalizationMethod.minmax: Linearly rescales samples so that the minimum maps to 0 and the maximum maps to 1 (or -1 to 1, depending on context).

  • NormalizationMethod.zscore: Applies z-score normalisation by subtracting the mean and dividing by the standard deviation.

  • NormalizationMethod.peak: Scales samples so that the maximum absolute amplitude equals 1.

  • NormalizationMethod.mean: Recentres samples by subtracting the mean value.

  • NormalizationMethod.median: Recentres samples by subtracting the median value.

Normalisation methods do not modify data eagerly; they describe how normalisation should be applied by downstream operations.

static default()
mean = <audio_samples.types.NormalizationMethod object>
median = <audio_samples.types.NormalizationMethod object>
minmax = <audio_samples.types.NormalizationMethod object>
peak = <audio_samples.types.NormalizationMethod object>
zscore = <audio_samples.types.NormalizationMethod object>
class audio_samples.types.OnsetDetectionConfig(cqt_params, hop_size, window_size=None, adaptive_threshold=True, median_filter_length=3, adaptive_threshold_multiplier=3.0, peak_picking=None)

Bases: object

Python wrapper for OnsetDetectionConfig.

Configuration for onset detection using spectral flux method.

Notes

The keyword defaults of the constructor OnsetDetectionConfig(cqt_params, hop_size, ...) are not those of OnsetDetectionConfig.default(): the constructor uses median_filter_length=3 and adaptive_threshold_multiplier=3.0, while default() uses 5 and 1.5 (other fields agree). Start from default() for the library defaults.

The global threshold, the minimum spacing between onsets and the pre-emphasis of the detection function are peak_picking settings.

peak_picking and cqt_params return copies; assign a modified copy back (config.peak_picking = pp) to change them.

adaptive_threshold

Get whether adaptive thresholding is enabled.

adaptive_threshold_multiplier

Get the adaptive threshold multiplier.

cqt_params

Get the CQT parameters.

classmethod default()

Create a default OnsetDetectionConfig.

explain(sample_rate=None, *, n_samples=None, n_channels=None, f0_range=None)

Explain what this onset-detection configuration will do.

Parameters:
  • sample_rate (float | None) – Sample rate in Hz of the signal it will be applied to. Without it, quantities that need a sample rate are omitted and an info warning says so.

  • n_samples (int | None) – Signal length in samples per channel.

  • n_channels (int | None) – Number of channels.

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

Returns:

The explanation (see audio_samples.explain).

Return type:

ExplainDoc

hop_size

Get the hop size in samples.

median_filter_length

Get the median filter length.

classmethod musical(sample_rate)

Create an OnsetDetectionConfig optimized for general music.

Parameters:

sample_rate (int) – Sample rate of the audio the configuration will be applied to; the peak picker’s durations are converted to frames at sample_rate / hop_size.

peak_picking

Get the peak picking configuration.

Returns a copy: setting fields on the returned object does not change this config. Modify the copy and assign it back:

pp = config.peak_picking
pp.min_peak_separation = 256
config.peak_picking = pp
classmethod percussive(sample_rate)

Create an OnsetDetectionConfig optimized for percussive sounds.

Parameters:

sample_rate (int) – Sample rate of the audio the configuration will be applied to; the peak picker’s durations are converted to frames at sample_rate / hop_size.

classmethod speech(sample_rate)

Create an OnsetDetectionConfig optimized for speech.

Parameters:

sample_rate (int) – Sample rate of the audio the configuration will be applied to; the peak picker’s durations are converted to frames at sample_rate / hop_size.

window_size

Get the window size in samples, or None if it defaults to CQT’s minimum window size.

class audio_samples.types.PadSide

Bases: object

Side for padding operations.

PadSide indicates which side of an audio signal should be padded when applying padding operations. It is used to specify whether padding should be added to the beginning (left) or end (right) of the signal.

static default()
left = <audio_samples.types.PadSide object>
right = <audio_samples.types.PadSide object>
class audio_samples.types.ParametricEq

Bases: object

Parametric equaliser configuration.

ParametricEq represents a complete parametric equaliser composed of an ordered collection of EQ bands. Each band shapes a specific region of the frequency spectrum, and the combined effect defines the overall frequency response.

Instances of ParametricEq are mutable. Bands can be added and removed after construction. The number of bands can be queried using len(eq) in Python.

add_band(band)

Add an EQ band to the equaliser.

Parameters:

band (EqBand) – Band configuration to append to the equaliser.

bypassed

Whether the equaliser is currently bypassed.

output_gain_db

Overall output gain in decibels.

remove_band(index)

Remove an EQ band by index.

Parameters:

index (int) – Zero-based index of the band to remove.

Returns:

The removed band if the index was valid, otherwise None.

Return type:

EqBand or None

class audio_samples.types.PeakPickingConfig(*, adaptive_threshold_config, min_peak_separation, pre_emphasis, pre_emphasis_coeff, median_filter, median_filter_length, normalize_onset_strength, normalization_method)

Bases: object

Configuration for peak picking with temporal constraints.

Peak picking identifies local maxima in the onset strength function that exceed a threshold. Temporal constraints ensure detected peaks are separated by minimum time intervals and can include smoothing.

Presets are class attributes, accessed without parentheses: PeakPickingConfig.music, PeakPickingConfig.speech, PeakPickingConfig.drums. PeakPickingConfig.default() is a method.

static default()
static drums(sample_rate, hop_size)

Drums preset: a 0.1 s percentile threshold window and 30 ms minimum separation.

The durations are converted to frames of the onset strength function at sample_rate / hop_size frames per second, so pass the sample rate and hop size of the onset function it will be applied to.

Parameters:
  • sample_rate (int) – Sample rate of the audio in Hz.

  • hop_size (int) – Hop between onset-function frames, in samples.

min_peak_separation

Minimum separation between detected peaks in frames.

static music(sample_rate, hop_size)

Music preset: a 0.2 s combined threshold window and 0.1 s minimum separation.

The durations are converted to frames of the onset strength function at sample_rate / hop_size frames per second, so pass the sample rate and hop size of the onset function it will be applied to.

Parameters:
  • sample_rate (int) – Sample rate of the audio in Hz.

  • hop_size (int) – Hop between onset-function frames, in samples.

set_median_filter(enabled, length)

Enable or disable median filtering.

set_min_peak_separation_ms(value, sample_rate)

Set minimum peak separation in milliseconds.

set_pre_emphasis(enabled, coeff)

Enable or disable pre-emphasis filtering.

static speech(sample_rate, hop_size)

Speech preset: a 0.2 s delta threshold window and 80 ms minimum separation.

The durations are converted to frames of the onset strength function at sample_rate / hop_size frames per second, so pass the sample rate and hop size of the onset function it will be applied to.

Parameters:
  • sample_rate (int) – Sample rate of the audio in Hz.

  • hop_size (int) – Hop between onset-function frames, in samples.

validate()

Validate the configuration parameters.

class audio_samples.types.PerturbationConfig(method, seed=None)

Bases: object

Configuration for audio perturbation operations.

PerturbationConfig defines how a perturbation method should be applied to audio data, optionally including a deterministic random seed.

The configuration is immutable once created. Validation can be performed explicitly using validate(sample_rate).

Typical usage is to construct a perturbation method first and then wrap it in a configuration object:

`python method = PerturbationMethod.gaussian(-12.0, NoiseColor.white) cfg = PerturbationConfig(method, seed=42).validate(sample_rate) `

seed

Random seed used for deterministic perturbation, if specified.

Returns:

The seed value, or None if no seed is configured.

Return type:

Optional[int]

validate(sample_rate)

Validate the perturbation configuration for a given sample rate.

Parameters:

sample_rate (float) – Sample rate in Hz, used to validate frequency-dependent parameters.

Returns:

This instance. Returned to allow call chaining.

Return type:

PerturbationConfig

Raises:

ValueError – If the configuration or underlying perturbation method is invalid.

class audio_samples.types.PerturbationMethod

Bases: object

Perturbation methods for audio data augmentation.

PerturbationMethod represents a specific audio perturbation configuration used for data augmentation, robustness testing, or creative effects.

This type is enum-like in Python. Instances are constructed via class constructors such as PerturbationMethod.gaussian(...) or PerturbationMethod.pitch_shift(...) rather than by calling PerturbationMethod() directly.

A perturbation configuration can be validated against a sample rate via validate(sample_rate).

classmethod brown_noise(target_snr_db)

Brown noise injection with a target signal-to-noise ratio.

Adds coloured Gaussian noise to achieve the target SNR relative to the input signal’s RMS level.

Parameters:

target_snr_db (float) – Target signal-to-noise ratio in decibels.

Returns:

A Gaussian-noise perturbation configuration.

Return type:

PerturbationMethod

classmethod gaussian(target_snr_db, noise_color)

Gaussian noise injection with a target signal-to-noise ratio.

Adds coloured Gaussian noise to achieve the target SNR relative to the input signal’s RMS level.

Parameters:
  • target_snr_db (float) – Target signal-to-noise ratio in decibels.

  • noise_color (NoiseColor) – Noise colour (spectral distribution) to use.

Returns:

A Gaussian-noise perturbation configuration.

Return type:

PerturbationMethod

classmethod high_pass_filter(cutoff_hz)

High-pass filtering perturbation.

Applies a high-pass filter to reduce low-frequency content, simulating effects such as rumble removal.

Parameters:

cutoff_hz (float) – High-pass cutoff frequency in Hz.

Returns:

A high-pass filter perturbation configuration.

Return type:

PerturbationMethod

classmethod high_pass_filter_with_slope(cutoff_hz, slope_db_per_octave)

High-pass filtering perturbation with custom slope.

Parameters:
  • cutoff_hz (float) – High-pass cutoff frequency in Hz.

  • slope_db_per_octave (float) – Filter slope in dB per octave.

Returns:

A high-pass filter perturbation configuration.

Return type:

PerturbationMethod

classmethod low_pass_filter(cutoff_hz)

Low-pass filtering perturbation.

Applies a low-pass filter to reduce high-frequency content, simulating effects such as telephone bandwidth limitation.

Parameters:

cutoff_hz (float) – Low-pass cutoff frequency in Hz.

Returns:

A low-pass filter perturbation configuration.

Return type:

PerturbationMethod

classmethod low_pass_filter_with_slope(cutoff_hz, slope_db_per_octave)

Low-pass filtering perturbation with custom slope.

Parameters:
  • cutoff_hz (float) – Low-pass cutoff frequency in Hz.

  • slope_db_per_octave (float) – Filter slope in dB per octave.

Returns:

A low-pass filter perturbation configuration.

Return type:

PerturbationMethod

classmethod pink_noise(target_snr_db)

Pink noise injection with a target signal-to-noise ratio.

Adds coloured Gaussian noise to achieve the target SNR relative to the input signal’s RMS level.

Parameters:

target_snr_db (float) – Target signal-to-noise ratio in decibels.

Returns:

A Gaussian-noise perturbation configuration.

Return type:

PerturbationMethod

classmethod pitch_shift(semitones, preserve_formants=False)

Pitch shifting perturbation.

Shifts the pitch of the signal by a number of semitones while attempting to maintain duration.

Parameters:
  • semitones (float) – Pitch shift in semitones. Positive shifts up; negative shifts down.

  • preserve_formants (bool, optional) – Whether to attempt formant preservation.

Returns:

A pitch-shift perturbation configuration.

Return type:

PerturbationMethod

classmethod random_gain(min_gain_db, max_gain_db)

Random gain perturbation within a specified range.

Applies a uniform random gain (in dB) to all channels. Positive values boost; negative values attenuate.

Parameters:
  • min_gain_db (float) – Minimum gain in decibels.

  • max_gain_db (float) – Maximum gain in decibels.

Returns:

A random-gain perturbation configuration.

Return type:

PerturbationMethod

validate(sample_rate)

Validate perturbation parameters for a given sample rate.

Parameters:

sample_rate (float) – Sample rate in Hz, used to validate frequency-dependent parameters.

Returns:

This instance. Returned to allow call chaining.

Return type:

PerturbationMethod

Raises:

ValueError – If the perturbation parameters are invalid.

classmethod white_noise(target_snr_db)

White noise injection with a target signal-to-noise ratio.

Adds coloured Gaussian noise to achieve the target SNR relative to the input signal’s RMS level.

Parameters:

target_snr_db (float) – Target signal-to-noise ratio in decibels.

Returns:

A Gaussian-noise perturbation configuration.

Return type:

PerturbationMethod

class audio_samples.types.PitchClass

Bases: object

One of the twelve pitch classes of the chromatic scale.

PitchClass represents a pitch class independent of octave. Pitch class C has index 0, ascending chromatically to B at index 11.

Instances of PitchClass are immutable and should be treated as enum-like values. They are accessed via class attributes, or constructed from a chromatic index via PitchClass.from_index(index).

Available pitch classes:

  • PitchClass.c, PitchClass.c_sharp, PitchClass.d, PitchClass.d_sharp, PitchClass.e, PitchClass.f, PitchClass.f_sharp, PitchClass.g, PitchClass.g_sharp, PitchClass.a, PitchClass.a_sharp, PitchClass.b.

a = PitchClass(A)
a_sharp = PitchClass(A#)
b = PitchClass(B)
c = PitchClass(C)
c_sharp = PitchClass(C#)
d = PitchClass(D)
d_sharp = PitchClass(D#)
e = PitchClass(E)
f = PitchClass(F)
f_sharp = PitchClass(F#)
static from_index(index)

Construct a pitch class from a chromatic index in 0..=11.

Parameters:

index (int) – Chromatic index where 0 maps to C and 11 maps to B.

Returns:

The pitch class for the given index.

Return type:

PitchClass

Raises:

ValueError – If index is greater than 11.

g = PitchClass(G)
g_sharp = PitchClass(G#)
to_index()

The chromatic index of this pitch class (C = 0, B = 11).

class audio_samples.types.PitchContour

Bases: object

A time-ordered pitch track.

PitchContour is a sequence of [PitchFrame] values produced by pitch tracking. Each frame pairs a frame onset time with the pitch detected in that frame (or None when no pitch was found).

Instances are produced by pitch tracking and are not constructed directly from Python.

frames()

All frames in time order, voiced and unvoiced alike.

Returns:

The complete list of pitch frames.

Return type:

list[PitchFrame]

mean_pitch()

The mean of all voiced frequencies, or None when no frame is voiced.

voiced_frames()

Voiced frames as (time_seconds, frequency_hz) pairs.

Unvoiced frames are skipped.

Returns:

The voiced frames as (time, frequency) tuples.

Return type:

list[tuple[float, float]]

class audio_samples.types.PitchDetectionMethod

Bases: object

Pitch detection algorithm selection.

PitchDetectionMethod selects the algorithm used to estimate the fundamental frequency of a signal. Different algorithms trade off accuracy, robustness to noise and inharmonicity, latency, and computational cost.

Instances of PitchDetectionMethod are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available methods:

  • PitchDetectionMethod.yin

  • PitchDetectionMethod.autocorrelation

  • PitchDetectionMethod.cepstrum (not implemented)

  • PitchDetectionMethod.harmonic_product (not implemented)

Notes

Only yin and autocorrelation are implemented. track_pitch raises AudioParameterError for cepstrum and harmonic_product.

autocorrelation = <audio_samples.types.PitchDetectionMethod object>
cepstrum = <audio_samples.types.PitchDetectionMethod object>
static default()
harmonic_product = <audio_samples.types.PitchDetectionMethod object>
yin = <audio_samples.types.PitchDetectionMethod object>
class audio_samples.types.PitchFrame(time, frequency=None)

Bases: object

A single frame of a pitch contour.

PitchFrame pairs a frame onset time with the fundamental frequency detected in that frame. The frequency is None for unvoiced frames where no pitch was detected.

Fields are exposed via read-only properties.

frequency

Detected fundamental frequency in Hz, or None if the frame is unvoiced.

time

Frame onset time, in seconds from the start of the signal.

voiced

Whether this frame is voiced (a pitch was detected).

class audio_samples.types.Psd

Bases: object

Power spectral density (PSD) estimate.

Psd pairs a frequency axis with the estimated power-per-Hz at each bin. The two arrays are always the same length: frequencies[i] is the centre frequency of bin i in Hz, and density[i] is the estimated power spectral density at that frequency.

Instances of Psd are produced by the power spectral density transform and are not constructed directly from Python. The frequency and density data are exposed as NumPy arrays.

density

The estimated power spectral density (power per Hz) at each frequency bin.

Returns:

A 1-D array of power-per-Hz values. Same length as frequencies.

Return type:

numpy.ndarray

frequencies

The frequency axis, in Hz.

Returns:

A 1-D array of bin centre frequencies in Hz. Same length as density.

Return type:

numpy.ndarray

into_parts()

Return the (frequencies, density) arrays as a tuple.

Returns:

A pair of 1-D NumPy arrays containing the frequency axis and the density values respectively.

Return type:

tuple[numpy.ndarray, numpy.ndarray]

class audio_samples.types.ResamplingQuality

Bases: object

Quality level for resampling operations.

Every tier is delay-free (output sample k is the input reconstructed at time k * in_rate / out_rate) and produces exactly ceil(n * out_rate / in_rate) samples; the tiers differ in the anti-aliasing / anti-imaging filter (Nyquist of the lower rate):

  • ResamplingQuality.fast (the default of AudioSamples.resample): short windowed sinc when downsampling (passband 0.80 x Nyquist, 70 dB stopband); linear interpolation when upsampling (images not suppressed).

  • ResamplingQuality.medium: windowed sinc, passband 0.90 x Nyquist, 100 dB stopband.

  • ResamplingQuality.high: windowed sinc, passband 0.913 x Nyquist, 125 dB stopband.

  • ResamplingQuality.very_high: windowed sinc, 185 dB stopband (limited to about -140 dB by rounding for float32 audio); 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).

Instances are immutable enum-like values accessed via the class attributes; resampling methods also accept the names "fast", "medium", "high" and "very_high".

static default()
fast = <audio_samples.types.ResamplingQuality object>
high = <audio_samples.types.ResamplingQuality object>
medium = <audio_samples.types.ResamplingQuality object>
very_high = <audio_samples.types.ResamplingQuality object>
class audio_samples.types.SampleType

Bases: object

Enumeration of supported audio sample data types.

SampleType describes the numeric representation used to store individual audio samples. It is typically used when constructing or converting audio buffers, configuring I/O, or selecting internal processing formats.

The available sample types are:

  • SampleType.I16: Signed 16-bit integer samples. Common in PCM WAV files and efficient for storage and I/O, but with limited dynamic range.

  • SampleType.I24: Signed 24-bit integer samples. Higher dynamic range than 16-bit PCM and widely used in professional audio pipelines.

  • SampleType.I32: Signed 32-bit integer samples. Rare in interchange formats, but sometimes used for intermediate or high-precision processing.

  • SampleType.F32 (default): 32-bit floating-point samples. The most common format for DSP and machine learning workloads due to good numerical stability and performance.

  • SampleType.F64: 64-bit floating-point samples. Provides maximum numerical precision at the cost of higher memory usage and lower throughput.

Instances of SampleType are immutable and comparable. They should be treated as enum values rather than constructed directly.

F32 = SampleType.F32
F64 = SampleType.F64
I16 = SampleType.I16
I24 = SampleType.I24
I32 = SampleType.I32
U8 = SampleType.U8
class audio_samples.types.SideChainConfig(enabled, high_pass_freq=None, low_pass_freq=None, pre_emphasis_db=0.0, external_mix=1.0)

Bases: object

Side-chain configuration for dynamic range processing.

SideChainConfig describes how an external or filtered control signal is used to drive gain reduction in dynamics processors such as compressors and limiters.

When enabled, the compressor and limiter build their detector input from the main signal x and, in the *_sidechain methods, the side-chain signal s as (1 - external_mix) * x + external_mix * s, then filter it with a 2nd-order Butterworth high-pass at high_pass_freq, a 2nd-order Butterworth low-pass at low_pass_freq and a first-order high shelf of pre_emphasis_db. Only the detector is filtered, never the signal path.

Instances of SideChainConfig are immutable value objects in the Python API. Parameters are provided at construction time and exposed via read-only properties.

static default()
enabled

Whether side-chain processing is enabled.

external_mix

Mix ratio between internal and external side-chain signal.

Values are expected in the range [0.0, 1.0].

high_pass_freq

High-pass filter cutoff frequency in Hz for the side-chain signal, if set.

low_pass_freq

Low-pass filter cutoff frequency in Hz for the side-chain signal, if set.

pre_emphasis_db

Pre-emphasis applied to the side-chain signal in decibels.

class audio_samples.types.SosFilter

Bases: object

Streaming second-order-sections (SOS) IIR filter.

A SosFilter is a cascade of biquad sections built once from an IirFilterDesign and then driven sample-by-sample or block-by-block. Internal delay-line state persists across calls, so processing consecutive blocks produces exactly the same result as processing the whole signal at once. This makes it suitable for real-time and streaming use where redesigning the filter for every block would be wasteful.

Build one with from_design(); the sample rate is fixed at construction time and used for all frequency-dependent computations.

filtfilt(samples)

Zero-phase forward-backward filtering of a whole signal.

The signal is extended at both ends by odd reflection and each pass starts from the steady-state initial conditions for its first sample. The streaming state is neither used nor modified. Returns a new array.

Parameters:

samples (np.typing.NDArray[np.float64]) – The whole signal.

Returns:

Filtered signal, same length.

Return type:

np.typing.NDArray[np.float64]

frequency_response(frequencies)

Compute the frequency response of the cascade.

Evaluates the combined transfer function of all sections. The magnitude is the product of section magnitudes; the phase is the sum of section phases. The sample rate fixed at construction is used.

Parameters:

frequencies (np.typing.NDArray[np.float64]) – Frequencies in hertz.

Returns:

Magnitude and phase (radians) arrays, each the same length as frequencies.

Return type:

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

static from_design(design, sample_rate)

Build a streaming SOS filter from a filter design.

Designs the filter once and returns a stateful cascade. The returned filter starts with zeroed delay lines.

Parameters:
  • design (IirFilterDesign) – Filter specification (type, order, frequencies, ripple/attenuation).

  • sample_rate (float) – Sample rate of the signal in hertz.

Returns:

A freshly-reset streaming filter implementing the design.

Return type:

SosFilter

Raises:

AudioError – If the design is invalid (out-of-range frequency, unsupported response, order too high, etc.).

static from_sos(sos, sample_rate)

Build a streaming filter from second-order-section coefficients.

Accepts the (n_sections, 6) array returned by scipy.signal.butter(..., output='sos') (and friends) or by IirFilterDesign.sos(), with rows [b0, b1, b2, a0, a1, a2].

Parameters:
  • sos (np.typing.NDArray[np.float64]) – Section coefficients, shape (n, 6).

  • sample_rate (float) – Sample rate in hertz (used by frequency_response()).

Raises:

ValueError – If the array is not (n, 6), is empty, contains non-finite values, or has a zero a0.

process_block(block)

Process a block of samples in place, retaining state across calls.

Alias of process_samples_in_place() with a name that signals the design-once / stream-many usage. Because delay lines persist, calling process_block on consecutive blocks of a signal yields exactly the same result as one call over the whole signal.

Parameters:

block (np.typing.NDArray[np.float64]) – Input/output block; modified in place.

Returns:

The provided array is modified in place.

Return type:

None

process_sample(x)

Process a single sample through the cascade.

Feeds x through each section in order; internal state is updated.

Parameters:

x (float) – Input sample.

Returns:

The filtered output sample.

Return type:

float

process_samples(samples)

Process an array of samples, returning a new array.

Equivalent to calling process_sample() for each input in order; state carries across the whole array.

Parameters:

samples (np.typing.NDArray[np.float64]) – Input samples.

Returns:

Filtered output, same length as input.

Return type:

np.typing.NDArray[np.float64]

process_samples_in_place(samples)

Process an array of samples in place.

Overwrites each element of samples with its filtered value. The input array is modified directly.

Parameters:

samples (np.typing.NDArray[np.float64]) – Input/output buffer; modified in place.

Returns:

The provided array is modified in place.

Return type:

None

reset()

Reset all sections’ delay lines to zero.

After a reset the cascade behaves identically to a freshly built filter with the same coefficients.

Returns:

None.

sos()

The filter’s second-order sections as a (n_sections, 6) array (SciPy sos layout, a0 normalised to 1).

class audio_samples.types.SpectralFluxConfig(*, cqt_params, hop_size, window_size=None, flux_method, peak_picking, rectify, log_compression)

Bases: object

Configuration for spectral flux onset detection.

Spectral flux measures the rate of change of the magnitude spectrum between consecutive frames, providing effective onset detection for both percussive and tonal instruments.

complex = SpectralFluxConfig { cqt_params: CqtParams { bins_per_octave: 24, n_octaves: 6, f_min: 55.0, q_factor: 34.12708770892056, window: Hanning, sparsity_threshold: 0.02, normalize: true }, hop_size: 512, window_size: None, flux_method: RectifiedComplex, peak_picking: PeakPickingConfig { adaptive_threshold: AdaptiveThresholdConfig { method: Delta, delta: 0.07, percentile: 0.9, window_size: 9, min_threshold: 0.1, max_threshold: 1.0 }, min_peak_separation: 3, pre_emphasis: false, pre_emphasis_coeff: 0.97, median_filter: false, median_filter_length: 3, normalize_onset_strength: true, normalization_method: Peak }, rectify: false, log_compression: 0.0 }
cqt_params

Get the CQT parameters.

flux_method

Get the spectral flux computation method.

hop_size

Get the hop size in samples.

log_compression

Get the logarithmic compression factor.

static musical(sample_rate)

Musical preset configuration.

Parameters:

sample_rate (int) – Sample rate of the audio the configuration will be applied to; the peak picker’s durations are converted to frames at sample_rate / hop_size.

peak_picking

Get the peak picking configuration.

Returns a copy: setting fields on the returned object does not change this config. Modify the copy and assign it back:

pp = config.peak_picking
pp.min_peak_separation = 256
config.peak_picking = pp
static percussive(sample_rate)

Percussive preset configuration.

Parameters:

sample_rate (int) – Sample rate of the audio the configuration will be applied to; the peak picker’s durations are converted to frames at sample_rate / hop_size.

rectify

Get whether to rectify the onset strength function.

validate()

Validate the configuration parameters.

window_size

Get the window size in samples, or None if it defaults to CQT’s minimum window size.

class audio_samples.types.SpectralFluxMethod

Bases: object

Spectral flux variant for onset detection.

Different flux formulations emphasise different types of spectral change and are therefore suited to different classes of musical and acoustic events.

complex = <audio_samples.types.SpectralFluxMethod object>
energy = <audio_samples.types.SpectralFluxMethod object>
magnitude = <audio_samples.types.SpectralFluxMethod object>
rectified_complex = <audio_samples.types.SpectralFluxMethod object>
class audio_samples.types.SpectrogramScale

Bases: object

Scaling method for spectrogram magnitude and frequency representations.

SpectrogramScale represents how spectral magnitudes or frequencies are mapped for analysis or visualisation. Different scaling approaches expose different structure in spectral content and are appropriate for different tasks.

Instances of SpectrogramScale are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available scales:

  • SpectrogramScale.linear

  • SpectrogramScale.log

  • SpectrogramScale.mel

static default()
linear = <audio_samples.types.SpectrogramScale object>
log = <audio_samples.types.SpectrogramScale object>
mel = <audio_samples.types.SpectrogramScale object>
class audio_samples.types.StereoConversionMethod

Bases: object

Method for converting mono audio to stereo.

StereoConversionMethod represents a strategy for expanding a mono signal into a two-channel stereo signal. Different methods control how the mono signal is distributed between the left and right channels.

Instances of StereoConversionMethod are immutable and should be treated as enum-like values. Zero-parameter methods are accessed via class attributes, while parameterised methods are constructed via class methods.

Available conversion methods:

  • StereoConversionMethod.duplicate

  • StereoConversionMethod.pan(pan_value)

  • StereoConversionMethod.left

  • StereoConversionMethod.right

static default()
duplicate = <audio_samples.types.StereoConversionMethod object>
left = <audio_samples.types.StereoConversionMethod object>
classmethod pan(pan_value)

Pan the mono signal between left and right channels.

A value of -1 places the signal fully in the left channel, 0 centres the signal, and 1 places it fully in the right channel.

Parameters:

pan_value (float) – Pan position in the range [-1, 1].

right = <audio_samples.types.StereoConversionMethod object>
class audio_samples.types.ThreeBandEqConfig(*, low_freq, low_gain, mid_freq, mid_gain, mid_q, high_freq, high_gain)

Bases: object

Three-band parametric equaliser configuration.

ThreeBandEqConfig describes a simple three-band equaliser composed of a low shelf, a mid peaking band, and a high shelf. It is a convenience configuration for common tone-shaping tasks without constructing individual EQ bands.

Instances of ThreeBandEqConfig are immutable value objects in the Python API. Parameters are provided at construction time and exposed via read-only properties. Validation can be performed explicitly using validate().

A flat (unity-gain) preset is provided via ThreeBandEqConfig.flat.

static default()
flat = ThreeBandEqConfig { low_freq: 200.0, low_gain: 0.0, mid_freq: 1000.0, mid_gain: 0.0, mid_q: 1.0, high_freq: 4000.0, high_gain: 0.0 }
high_freq

High shelf corner frequency in Hz.

high_gain

High shelf gain in dB.

low_freq

Low shelf corner frequency in Hz.

low_gain

Low shelf gain in dB.

mid_freq

Mid peak centre frequency in Hz.

mid_gain

Mid peak gain in dB.

mid_q

Mid peak Q factor.

validate()

Validate the three-band EQ parameters.

Returns:

The validated configuration.

Return type:

ThreeBandEqConfig

Raises:

ValueError – If any configuration parameter is invalid (non-positive frequency, mis-ordered frequencies, or non-positive mid Q).

class audio_samples.types.VadChannelPolicy

Bases: object

Multi-channel handling policy for Voice Activity Detection (VAD).

VadChannelPolicy defines how voice activity decisions are produced when the input audio contains multiple channels. Different policies determine whether channels are mixed, evaluated independently, or selected explicitly.

Instances of VadChannelPolicy are immutable and should be treated as enum-like values. Zero-parameter policies are accessed via class attributes, while parameterised policies are constructed via class methods.

Available policies:

  • VadChannelPolicy.average_to_mono

  • VadChannelPolicy.any_channel

  • VadChannelPolicy.all_channels

  • VadChannelPolicy.channel(ch)

all_channels = AllChannels
any_channel = AnyChannel
average_to_mono = AverageToMono
classmethod channel(ch)

Run VAD on a specific channel index.

Parameters:

ch (int) – Zero-based channel index to use for VAD.

static default()
class audio_samples.types.VadConfig(method, channel_policy, /, frame_size, hop_size, pad_end, energy_threshold_db, zcr_min, zcr_max, min_speech_frames, min_silence_frames, hangover_frames, smooth_frames, speech_band_low_hz, speech_band_high_hz, spectral_ratio_threshold)

Bases: object

Configuration for Voice Activity Detection (VAD).

VadConfig defines all parameters controlling frame-based voice activity detection. The VAD operates on overlapping frames of length frame_size with step hop_size and produces a boolean decision per frame.

Defaults are chosen to work reasonably well for general audio, but most applications should tune thresholds and timing parameters for their content and sample format.

Instances are immutable once constructed. Use validate() to check that a configuration is internally consistent.

A convenience preset is available via VadConfig.energy_only.

channel_policy

Policy for multi-channel audio.

static default()
energy_only = VadConfig { method: Energy, frame_size: 1024, hop_size: 512, pad_end: true, channel_policy: AverageToMono, energy_threshold_db: -40.0, zcr_min: 0.02, zcr_max: 0.3, min_speech_frames: 3, min_silence_frames: 5, hangover_frames: 2, smooth_frames: 5, speech_band_low_hz: 300.0, speech_band_high_hz: 3400.0, spectral_ratio_threshold: 0.6 }
energy_threshold_db

Energy threshold in dBFS (frame RMS).

explain(sample_rate=None, *, n_samples=None, n_channels=None, f0_range=None)

Explain what this voice-activity-detection configuration will do.

Parameters:
  • sample_rate (float | None) – Sample rate in Hz of the signal it will be applied to. Without it, quantities that need a sample rate are omitted and an info warning says so.

  • n_samples (int | None) – Signal length in samples per channel.

  • n_channels (int | None) – Number of channels.

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

Returns:

The explanation (see audio_samples.explain).

Return type:

ExplainDoc

frame_size

Analysis frame length in samples.

hangover_frames

speech stays active this many frames after energy drops.

Type:

Hangover in frames

hop_size

Hop size in samples (frame step).

method

VAD method.

min_silence_frames

Minimum number of consecutive non-speech frames to keep a silence region.

min_speech_frames

Minimum number of consecutive speech frames to keep a speech region.

pad_end

Whether to include a final partial frame (zero-padded).

smooth_frames

Majority-vote smoothing window in frames (1 = no smoothing).

spectral_ratio_threshold

Threshold on the speech-band energy ratio (VadMethod.spectral).

speech_band_high_hz

Upper bound of the speech band in Hz (VadMethod.spectral).

speech_band_low_hz

Lower bound of the speech band in Hz (VadMethod.spectral).

validate()

Validate configuration parameters.

Checks internal parameter consistency and value ranges. An exception is raised if any constraint is violated.

Returns:

Returns the validated configuration if validation succeeds.

Return type:

VadConfig

Raises:

ValueError – If any configuration parameter is invalid or inconsistent.

zcr_max

Maximum zero-crossing rate, in crossings per sample ([0, 1]).

zcr_min

Minimum zero-crossing rate, in crossings per sample ([0, 1]).

class audio_samples.types.VadMethod

Bases: object

Voice Activity Detection (VAD) method.

VadMethod represents the algorithmic strategy used to detect regions of speech or activity within an audio signal. Different methods trade off computational cost, robustness to noise, and detection accuracy.

Instances of VadMethod are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

Available VAD methods:

  • VadMethod.energy

  • VadMethod.zcr (zero crossing rate)

  • VadMethod.combined

  • VadMethod.spectral

combined = Combined
static default()
energy = Energy
spectral = Spectral
zcr = ZeroCrossing
class audio_samples.types.WindowType

Bases: object

Window function for spectral analysis and filtering.

WindowType represents a predefined window function applied to signals prior to FFT-based analysis or filtering. Different window types trade off frequency resolution against spectral leakage and side-lobe suppression.

Instances of WindowType are immutable and should be treated as enum-like values. They are accessed via class attributes rather than being constructed directly.

The window types are:

  • WindowType.hanning

  • WindowType.hamming

  • WindowType.blackman

  • WindowType.rectangular

blackman = <audio_samples.types.WindowType object>
static default()
classmethod gaussian(std)

Gaussian window.

Smooth window with a parameter controlling the effective width of the window.

Parameters:

std (float) – Standard deviation controlling the width of the Gaussian envelope.

hamming = <audio_samples.types.WindowType object>
hanning = <audio_samples.types.WindowType object>
classmethod kaiser(beta)

Kaiser window.

Parameterised window providing a tunable trade-off between main-lobe width and side-lobe attenuation.

Parameters:

beta (float) – Controls the trade-off between frequency resolution and spectral leakage. Larger values increase side-lobe suppression at the cost of wider main lobes.

rectangular = <audio_samples.types.WindowType object>