librosa.onset.onset_strength#
- librosa.onset.onset_strength(*, y=None, sr=22050, S=None, lag=1, max_size=1, ref=None, detrend=False, center=True, feature=None, aggregate=None, top_db=80.0, mode=None, **kwargs)[source]#
Compute a spectral flux onset strength envelope.
In standard spectral flux mode (
mode="flux"), onset strength at timetis determined by:mean_f max(0, S[f, t] - ref[f, t - lag])
where
refisSafter local max filtering along the frequency axis [1].In complex-domain mode (
mode="complex"), onset strength models both energy dynamics and phase trajectory continuity [2] [3]. The complex phasor at frametis predicted by extrapolating the phase advance from reference framet - lag, and the onset envelope measures the Euclidean residual between the target phasor and predicted phasor under non-decreasing magnitude.By default, if a time series
yis provided:In
"flux"mode:Swill be the log-power Mel spectrogram.In
"complex"mode:Swill be the complex STFT.
- Parameters:
- ynp.ndarray [shape=(…, n)]
audio time-series. Multi-channel is supported.
- srnumber > 0 [scalar]
sampling rate of
y- Snp.ndarray [shape=(…, d, m)]
pre-computed spectrogram. Can be real-valued (magnitude/power) or complex-valued.
- lagint > 0
time lag for computing differences
- max_sizeint > 0
size (in frequency bins) of the local max filter. set to 1 to disable filtering. Must be 1 when
mode="complex".- refNone or np.ndarray [shape=(…, d, m)]
An optional pre-computed reference spectrum, of the same shape as
S. If not provided, it will be computed fromS. If provided, it will override any local max filtering governed bymax_size. Must be None whenmode="complex".- detrendbool [scalar]
Filter the onset strength to remove the DC component
- centerbool [scalar]
Shift the onset function by
n_fft // (2 * hop_length)frames. This corresponds to using a centered frame analysis in the short-time Fourier transform.- featurefunction, optional
Function for computing time-series features (spectrograms). By default:
In
"flux"mode: useslibrosa.feature.melspectrogramwithfmax=sr/2and log-amplitude scaling (power_to_db).In
"complex"mode: useslibrosa.core.stftto preserve complex phase.
If a custom callable is provided, arguments are filtered to match its signature, allowing functions like
librosa.stft,librosa.cqt,librosa.vqt, or custom callables to be passed directly.- aggregatefunction
Aggregation function to use when combining onsets at different frequency bins.
Default:
np.mean- top_dbfloat or None
Threshold the spectrogram at
top_dbbelow its peak before the dB conversion in"flux"mode, as in power_to_db. PassNoneto disable thresholding. Ignored whenmode="complex".- mode{“flux”, “complex”} or None, default=None
Computation mode for onset strength:
None: infer automatically fromSif provided ("complex"if numpy.iscomplexobj(S) else"flux"); defaults to"flux"if(y, sr)is provided."flux": standard spectral flux (rectified spectral difference)."complex": complex-domain spectral flux.
- **kwargsadditional keyword arguments
Additional parameters to
feature(), ifSis not provided.
- Returns:
- onset_envelopenp.ndarray [shape=(…, m,)]
vector containing the onset strength envelope. If the input contains multiple channels, then onset envelope is computed for each channel.
- Raises:
- ParameterValueError
if neither
(y, sr)norSare providedor if
lagormax_sizeare not positive integersor if
modeis not one ofNone,"flux", or"complex"or if
mode="complex"andmax_size > 1or if
mode="complex"andref is not Noneor if
mode="complex"andS(orfeature(...)) is real-valued
See also
Examples
First, load some audio and plot the spectrogram
>>> import matplotlib.pyplot as plt >>> y, sr = librosa.loadx("trumpet", duration=3) >>> D = np.abs(librosa.stft(y)) >>> times = librosa.times_like(D, sr=sr) >>> fig, ax = plt.subplots(nrows=4, sharex=True, height_ratios=[3, 1, 1, 1]) >>> librosa.display.specshow( ... D, vscale="dBFS", y_axis="log", x_axis="time", ax=ax[0], sr=sr ... ) >>> ax[0].set(title="Power spectrogram") >>> ax[0].label_outer()
Construct a standard onset function
>>> onset_env = librosa.onset.onset_strength(y=y, sr=sr) >>> ax[1].plot( ... times, ... onset_env / onset_env.max(), ... alpha=0.8, ... label="Mean (mel)", ... color="C0", ... ) >>> ax[1].label_outer()
Compute complex-domain onset strength
>>> onset_complex = librosa.onset.onset_strength(y=y, sr=sr, mode="complex") >>> ax[2].plot( ... times, ... onset_complex / onset_complex.max(), ... alpha=0.8, ... label="Complex domain (STFT)", ... color="C1", ... ) >>> ax[2].label_outer()
Constant-Q spectrogram instead of Mel
>>> C = np.abs(librosa.cqt(y=y, sr=sr)) >>> onset_cqt = librosa.onset.onset_strength( ... sr=sr, S=librosa.amplitude_to_db(C, ref=np.max) ... ) >>> ax[3].plot( ... times, ... onset_cqt / onset_cqt.max(), ... alpha=0.8, ... label="Mean (CQT)", ... color="C2", ... ) >>> ax[3].label_outer() >>> fig.legend(loc="center right", ncols=3)