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 time t is determined by:

mean_f max(0, S[f, t] - ref[f, t - lag])

where ref is S after 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 frame t is predicted by extrapolating the phase advance from reference frame t - 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 y is provided:

  • In "flux" mode: S will be the log-power Mel spectrogram.

  • In "complex" mode: S will 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 from S. If provided, it will override any local max filtering governed by max_size. Must be None when mode="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: uses librosa.feature.melspectrogram with fmax=sr/2 and log-amplitude scaling (power_to_db).

  • In "complex" mode: uses librosa.core.stft to 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_db below its peak before the dB conversion in "flux" mode, as in power_to_db. Pass None to disable thresholding. Ignored when mode="complex".

mode{“flux”, “complex”} or None, default=None

Computation mode for onset strength:

  • None: infer automatically from S if 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(), if S is 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) nor S are provided

or if lag or max_size are not positive integers

or if mode is not one of None, "flux", or "complex"

or if mode="complex" and max_size > 1

or if mode="complex" and ref is not None

or if mode="complex" and S (or feature(...)) is real-valued

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)
../../_images/librosa-onset-onset_strength-1.png