Effects and Decomposition

Audio-to-audio effects are AudioSamples methods returning AudioSamples of the input’s sample type, each with an _in_place variant; array-level functions live in audio_samples.effects.

  • Time and pitch: AudioSamples.time_stretch, pitch_shift, resample; effects.phase_vocoder on an STFT.

  • Emphasis: AudioSamples.preemphasis / deemphasis; effects.preemphasis / deemphasis with filter state (zi, return_zf).

  • Silence: AudioSamples.trim_db and split_db (frames within top_db of the reference), remix (concatenate intervals).

  • Harmonic/percussive separation: AudioSamples.harmonic, percussive, harmonic_percussive; effects.hpss and effects.softmask on spectrograms; effects.nn_filter.

  • Reconstruction and synthesis: effects.griffinlim / AudioSamples.griffinlim_audio, effects.clicks.

  • Linear prediction and companding: AudioSamples.lpc / effects.lpc, AudioSamples.mu_compress / mu_expand, mu_law_encode / mu_law_decode.

trim_db, split_db and harmonic_percussive are separate from AudioSamples.trim, split and hpss, which work differently.

pitch_shift and resample use this library’s delay-free windowed-sinc resampler (res_type="soxr_hq" maps to ResamplingQuality.high); trim_db raises ValueError when everything is silent (an AudioSamples cannot be empty); harmonic/percussive use the window argument and do not accept mask=True; Griffin-Lim’s random initial phases come from this library’s RNG and init=None starts from zero phase; clicks returns float64 unless asked for float32; nn_filter takes dense recurrence matrices and the mean, median or weighted-average aggregates only.

Effect and decomposition functions over NumPy arrays (phase vocoder, pre-/de-emphasis with filter state, soft masks, HPSS, nearest-neighbour filtering, Griffin-Lim, LPC, click tracks). float32 / complex64 arrays are processed in float32 and give float32 output; any other input is converted to float64.

AudioSamples methods

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

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

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

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

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

AudioSamples.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]

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

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

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

AudioSamples.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]

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

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

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

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

Array functions

audio_samples.effects.phase_vocoder(D, *, rate=None, t_out=None, kind='linear', hop_length=None, n_fft=None)

Time-stretches an STFT matrix with a phase vocoder.

Give exactly one of rate (output frames at 0, rate, 2 rate, ...) or t_out (explicit fractional frame positions in [0, n_frames)). Magnitudes are linearly interpolated; the phase accumulates the raw frame-to-frame phase differences.

Parameters:
  • D (array_like) – complex STFT of shape (n_bins, n_frames) or (channels, n_bins, n_frames).

  • rate (Optional[float]) – Speed-up factor (> 1 is faster / fewer frames).

  • t_out (Optional[array_like]) – Output frame positions.

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

  • hop_length (Optional[int]) – Deprecated and unused (the phase advance cancels); accepted with a FutureWarning when given.

  • n_fft (Optional[int]) – Deprecated and unused, as hop_length.

Returns:

shape (n_bins, ceil(n_frames / rate)) (or len(t_out) frames), with a leading channel axis for 3-D input.

Return type:

numpy.ndarray[complex64 | complex128]

Raises:

ValueError – If neither or both of rate / t_out are given, or a value is out of range.

audio_samples.effects.preemphasis(y, *, coef=0.97, zi=None, return_zf=False)

Pre-emphasis filter y[n] = x[n] - coef * x[n - 1].

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

  • coef (float) – Coefficient. Default 0.97.

  • zi (Optional[float | array_like]) – Initial filter state (one value, or one per channel). None uses 2 * y[0] - y[1].

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

Returns:

numpy.ndarray[float32 | float64] of the input’s shape, or (y, zf) with return_zf=True (zf of shape (1,) or (channels, 1)).

Raises:

ValueError – For a non-finite coef / zi, or fewer than two samples with the default zi.

audio_samples.effects.deemphasis(y, *, coef=0.97, zi=None, return_zf=False)

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

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

  • coef (float) – Coefficient. Default 0.97 (3 only with an explicit zi).

  • zi (Optional[float | array_like]) – Initial filter state. None uses the state that exactly inverts preemphasis with its default state.

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

Returns:

numpy.ndarray[float32 | float64] of the input’s shape, or (y, zf).

Raises:

ValueError – As preemphasis.

audio_samples.effects.softmask(X, X_ref, *, power=1, split_zeros=False)

Soft mask X**p / (X**p + X_ref**p).

Parameters:
  • X (array_like) – Non-negative values selected by the mask.

  • X_ref (array_like) – Non-negative reference, same shape.

  • power (float) – Exponent (> 0). numpy.inf gives a hard (bool) mask X > X_ref. Default 1.

  • split_zeros (bool) – Mask value where both inputs are zero: 0.5 if True, else 0. Default False.

Returns:

values in [0, 1] in X’s precision (bool for power=inf), same shape.

Return type:

numpy.ndarray

Raises:

ValueError – For mismatched shapes, negative input or power <= 0.

audio_samples.effects.hpss(S, *, kernel_size=31, power=2.0, mask=False, margin=1.0)

Median-filtering harmonic/percussive separation of a spectrogram.

H is |S| median-filtered along time, P along frequency (edges mirrored, edge sample repeated); the masks are softmask(H, margin_h * P) and softmask(P, margin_p * H).

Parameters:
  • S (array_like) – Magnitude/power spectrogram (real, non-negative) or complex STFT, shape (n_bins, n_frames) or (channels, n_bins, n_frames).

  • kernel_size (int | tuple[int, int]) – Median filter lengths (harmonic along time, percussive along frequency). Default 31.

  • power (float) – Mask exponent (numpy.inf for hard masks). Default 2.

  • mask (bool) – Return the masks instead of the components. Default False.

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

Returns:

(harmonic, percussive) of the input’s shape and dtype (complex input keeps its phase), or with mask=True the masks in S’s precision (bool for power=inf).

Return type:

tuple

Raises:

ValueError – For invalid parameters or negative magnitudes.

audio_samples.effects.nn_filter(S, *, rec=None, aggregate=None, axis=-1, **kwargs)

Nearest-neighbour filtering of a feature matrix.

Each frame is replaced by an aggregate of its neighbours in a recurrence matrix (rec[j, i] != 0 links frame j to output frame i); frames without neighbours are copied.

Parameters:
  • S (array_like) – Features (n_features, n_frames).

  • rec (Optional[array_like]) – (n_frames, n_frames) recurrence matrix, dense (bool or float) or scipy.sparse in any format, where every stored entry is a neighbour. None computes audio_samples.sequence.recurrence_matrix(S, **kwargs).

  • aggregate – None / numpy.mean (default), numpy.median, numpy.average (weighted by rec; use an affinity matrix), numpy.max, numpy.min, numpy.sum, or any callable f(neighbours, axis=0) of the (n_neighbours, n_features) neighbours of a frame, which runs with the GIL held.

  • axis (int) – Must be -1.

  • **kwargs – recurrence_matrix arguments when rec is None: k, width, metric, sym, mode, bandwidth, self, full.

Returns:

filtered (n_features, n_frames).

Return type:

numpy.ndarray[float32 | float64]

Raises:
  • ValueError – For a wrong-shaped rec or invalid arguments.

  • TypeError – For an aggregate that is not callable or unknown keyword arguments.

audio_samples.effects.griffinlim(S, *, n_iter=32, hop_length=None, win_length=None, n_fft=None, window='hann', center=True, dtype=None, length=None, pad_mode='constant', momentum=0.99, init='random', rng=0, random_state=None)

Reconstructs a signal from a magnitude spectrogram with fast Griffin-Lim.

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

  • n_iter (int) – Iterations. Default 32.

  • hop_length – STFT parameters of S.

  • win_length – STFT parameters of S.

  • window – STFT parameters of S.

  • center – STFT parameters of S.

  • pad_mode – STFT parameters of S.

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

  • dtype – Ignored; the output follows S’s precision (float32 for a float32 S, float64 otherwise).

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

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

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

  • rng – Seed for init="random": an integer, None for a fresh seed on every call, or a NumPy generator or anything else numpy.random.default_rng takes, from which one seed is drawn (advancing the generator). The random phases come from this library’s generator.

  • random_state – Deprecated alias of rng.

Returns:

shape (n,) for 2-D S, (channels, n) for 3-D.

Return type:

numpy.ndarray[float32 | float64]

Raises:

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

audio_samples.effects.lpc(y, *, order, axis=-1)

Linear-prediction coefficients by Burg’s method.

Parameters:
  • y (array_like) – Finite signal (n,) or (channels, n) with more than order samples.

  • order (int) – Prediction order.

  • axis (int) – Must be -1.

Returns:

(order + 1,) coefficients [1, a_1, ...] ((channels, order + 1) for 2-D input).

Return type:

numpy.ndarray[float32 | float64]

Raises:

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

audio_samples.effects.clicks(*, times=None, frames=None, sr, hop_length=None, click_freq=1000.0, click_duration=0.1, click=None, length=None, dtype=None)

Synthesises a click track.

Parameters:
  • times (Optional[array_like]) – Click times in seconds.

  • frames (Optional[array_like]) – Click frame indices (used when times is None).

  • sr (int) – Sampling rate (a positive integer). Required.

  • hop_length (Optional[int]) – Samples per frame for frames. Required when frames is given; unused with times.

  • click_freq (float) – Frequency of the default click. Default 1000.

  • click_duration (float) – Duration of the default click (s). Default 0.1.

  • click (Optional[array_like]) – Custom 1-D click waveform.

  • length (Optional[int]) – Output length; clicks starting at or after it are dropped. None: up to the end of the last click.

  • dtype (Optional[numpy.dtype]) – Output dtype, numpy.float32 or numpy.float64. Default None: float64.

Returns:

1-D click signal (float64 unless dtype says otherwise).

Return type:

numpy.ndarray[float64 | float32]

Raises:

ValueError – If neither times nor frames is given, a time is negative, or parameters are invalid.