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_vocoderon an STFT.Emphasis:
AudioSamples.preemphasis/deemphasis;effects.preemphasis/deemphasiswith filter state (zi,return_zf).Silence:
AudioSamples.trim_dbandsplit_db(frames withintop_dbof the reference),remix(concatenate intervals).Harmonic/percussive separation:
AudioSamples.harmonic,percussive,harmonic_percussive;effects.hpssandeffects.softmaskon 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_vocoderbyrate, inverse STFT to exactlyround(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:
- Raises:
ValueError – If
rateis 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_stepswithout changing the duration.Time-stretch by
rate = 2 ** (-n_steps / bins_per_octave), resample byrate, 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 toResamplingQuality.high,"soxr_mq"tomediumand"soxr_lq"tofast.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:
- Raises:
ValueError – For a non-finite
n_steps,scale=Trueor invalid parameters.
- AudioSamples.preemphasis(*, coef=0.97)
Pre-emphasis
y[n] = x[n] - coef * x[n - 1]of every channel, with initial state2 x[0] - x[1]. Useaudio_samples.effects.preemphasisforzi/return_zf.- Parameters:
coef (float) – Coefficient. Default 0.97.
- Returns:
the filtered audio.
- Return type:
- Raises:
ValueError – For a non-finite
coefor fewer than two samples.
- AudioSamples.deemphasis(*, coef=0.97)
De-emphasis
y[n] = x[n] + coef * y[n - 1]of every channel (inverse ofpreemphasis).- Parameters:
coef (float) – Coefficient (not 3). Default 0.97.
- Returns:
the filtered audio.
- Return type:
- Raises:
ValueError – For a non-finite
coef,coef == 3or 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 withtrim_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.maxuses 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.meanor any callable, called asaggregate(db, 0)on the(channels, frames)levels in dB of multichannel audio. A callable here or inrefruns with the GIL held.
- Returns:
(trimmed, index): the trimmedAudioSamplesand an int64 array[start, end]of the kept sample range.- Return type:
- Raises:
ValueError – For invalid parameters, or if everything is silent (an
AudioSamplescannot be empty; usesplit_dbto test).
- AudioSamples.split_db(*, top_db, ref='max', frame_length=2048, hop_length=512, aggregate=None)
Non-silent intervals: frames within
top_dbof 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:
- 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. Thehpssmethod 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;
windowsets the STFT window.hop_length – STFT parameters;
windowsets the STFT window.win_length – STFT parameters;
windowsets the STFT window.window – STFT parameters;
windowsets the STFT window.center – STFT parameters;
windowsets the STFT window.pad_mode – STFT parameters;
windowsets the STFT window.
- Returns:
the harmonic component, same length.
- Return type:
- 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.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 (
hpssis 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:
- AudioSamples.lpc(*, order)
LPC coefficients of every channel (Burg’s method).
- Parameters:
order (int) – Prediction order; each channel needs more than
ordersamples.- 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). Seeaudio_samples.effects.griffinlimfor 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,rngasaudio_samples.effects.griffinlim(rngdefaults 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 float32Sand float64 audio for any other input. The reconstruction runs in the float type ofdtype(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.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:
- Raises:
ValueError – If
target_sample_rateis 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 exactlyresample(target_rate, quality)(delay-free, exactlyceil(n * target_rate / sample_rate)samples; seeresamplefor the quality tiers).- Parameters:
ratio (float) – Output rate / input rate (> 0).
quality (ResamplingQuality | str) – As
resample; default"fast".
- Returns:
the resampled audio at
round(sample_rate * ratio)Hz.- Return type:
- Raises:
ValueError – If
ratiois 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 at0, rate, 2 rate, ...) ort_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
FutureWarningwhen given.n_fft (Optional[int]) – Deprecated and unused, as
hop_length.
- Returns:
shape
(n_bins, ceil(n_frames / rate))(orlen(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_outare 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:
- Returns:
numpy.ndarray[float32 | float64] of the input’s shape, or
(y, zf)withreturn_zf=True(zfof shape(1,)or(channels, 1)).- Raises:
ValueError – For a non-finite
coef/zi, or fewer than two samples with the defaultzi.
- 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 ofpreemphasis).- 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
preemphasiswith 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.infgives a hard (bool) maskX > 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]inX’s precision (bool forpower=inf), same shape.- Return type:
- 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.
His|S|median-filtered along time,Palong frequency (edges mirrored, edge sample repeated); the masks aresoftmask(H, margin_h * P)andsoftmask(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.inffor 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 withmask=Truethe masks inS’s precision (bool forpower=inf).- Return type:
- 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] != 0links framejto output framei); 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) orscipy.sparsein any format, where every stored entry is a neighbour. None computesaudio_samples.sequence.recurrence_matrix(S, **kwargs).aggregate – None /
numpy.mean(default),numpy.median,numpy.average(weighted byrec; use an affinity matrix),numpy.max,numpy.min,numpy.sum, or any callablef(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_matrixarguments whenrecis 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
recor 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 float32S, 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 elsenumpy.random.default_rngtakes, 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-DS,(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:
- 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
timesis None).sr (int) – Sampling rate (a positive integer). Required.
hop_length (Optional[int]) – Samples per frame for
frames. Required whenframesis given; unused withtimes.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.float32ornumpy.float64. Default None: float64.
- Returns:
1-D click signal (float64 unless
dtypesays otherwise).- Return type:
numpy.ndarray[float64 | float32]
- Raises:
ValueError – If neither
timesnorframesis given, a time is negative, or parameters are invalid.