In [1]:
import numpy, scipy, matplotlib.pyplot as plt, pandas, librosa
Automatic detection of musical events in an audio signal is one of the most fundamental tasks in music information retrieval. Here, we will show how to detect an onset, the start of a musical event.
For more reading, see this tutorial on onset detection by Juan Bello.
Load the audio file simpleLoop.wav
into the NumPy array x
and sampling rate fs
.
In [2]:
x, fs = librosa.load('simpleLoop.wav', sr=44100)
print x.shape
Plot the signal:
In [3]:
librosa.display.waveplot(x, fs)
Out[3]:
Listen:
In [4]:
from IPython.display import Audio
Audio(x, rate=fs)
Out[4]:
librosa.onset.onset_detect
returns the frame indices for estimated onsets in a signal:
In [5]:
onsets = librosa.onset.onset_detect(x, fs)
print onsets # frame numbers of estimated onsets
Plot the onsets on top of a spectrogram of the audio:
In [6]:
S = librosa.stft(x)
logS = librosa.logamplitude(S)
librosa.display.specshow(logS, fs, alpha=0.75, x_axis='time')
plt.vlines(onsets, 0, logS.shape[0], color='r')
Out[6]:
The easiest way in Essentia to detect onsets given a time-domain signal is using OnsetRate
. It returns a list of onset times and the onset rate, i.e. number of onsets per second.
In [7]:
from essentia.standard import OnsetRate
find_onsets = OnsetRate()
onset_times, onset_rate = find_onsets(x)
print onset_times
print onset_rate
To verify our results, we can use AudioOnsetsMarker
to add a sound at the moment of each onset.
In [8]:
from essentia.standard import AudioOnsetsMarker
onsets_marker = AudioOnsetsMarker(onsets=onset_times, type='beep')
x_beeps = onsets_marker(x)
Audio(x_beeps, rate=fs)
Out[8]:
Sounds good!
For more control over the onset detection algorithm, see OnsetDetection
, OnsetDetectionGlobal
, and Onsets
.