Onset detection

The onset strength envelope and the peaks picked from it, as times in seconds.

import matplotlib.pyplot as plt
import numpy as np

import audio_samples as aus
from audio_samples import effects

Four decaying clicks half a second apart.

sr = 22050
times = np.array([0.25, 0.75, 1.25, 1.75])
y = effects.clicks(times=times, sr=sr, length=2 * sr, click_duration=0.05)
audio = aus.AudioSamples.new_mono(y.astype(np.float32), sr)
audio
AudioSamples
dtypef32
channels1 (mono)
sample rate22050 Hz
duration2.000 s (44100 samples per channel)
peak0.9587 (-0.4 dBFS)
RMS0.0600 (-24.4 dBFS)


envelope = audio.onset_strength()[0]
onsets = audio.onset_detect(units="time")
print(onsets)
assert np.max(np.abs(onsets - times)) < 0.05

t = np.arange(envelope.size) * 512 / sr
fig, ax = plt.subplots(figsize=(7, 3))
ax.plot(t, envelope, label="Onset strength")
ax.vlines(onsets, 0, envelope.max(), color="C3", ls="--", label="Detected onsets")
ax.set(xlabel="Time (s)", title="Onset detection")
ax.legend()
Onset detection
[0.2554195  0.7662585  1.25387755 1.76471655]

<matplotlib.legend.Legend object at 0x7efce5105590>

Total running time of the script: (0 minutes 0.082 seconds)