Detect the BPM of an Audio File in Python
To get the tempo of a file in Python, load it with libsonare.Audio.from_file and call detect_bpm(). It returns one float, the tempo in beats per minute. The script below prints it, then repeats the call with a narrower search range, which is the fix for the one mistake tempo detectors make most often.
python
from libsonare import Audio
with Audio.from_file("song.wav") as audio:
bpm = audio.detect_bpm()
print(f"{bpm:.1f} BPM ({audio.duration_sec:.1f} s at {audio.sample_rate} Hz)")
# Same file, search limited to 90-180 BPM.
print(f"{audio.detect_bpm(bpm_min=90.0, bpm_max=180.0):.1f} BPM in 90-180")The same measurement from a shell is sonare bpm song.wav --json, which has no search range option. WAV and MP3 are decoded by the engine itself; other formats need a build with FFmpeg. A stereo file is folded to mono on load.
What you need
- Install:
pip install libsonare(Python 3.11 or later; NumPy comes with it). Thesonarecommand ships with it. - An audio file: a song or loop with a beat. A 4.4 s loop at 120 BPM printed
120.3.
Reading the result
- Unit and precision. The value is beats per minute and is measured, not snapped to an integer, so a 120 BPM track reads a fraction away from 120. Round it for display.
bpm_minandbpm_maxare in BPM too. - Half or double tempo. A detector can lock onto every other beat, or onto the off-beats in between, and report 60 for a 120 BPM song. If you know the style, set
bpm_minandbpm_maxaround the tempos you expect; the answer is then taken from inside that window: on the 120 BPM loop above,bpm_min=40.0, bpm_max=70.0reads60.2, half time on purpose, and a window of 150 to 300 reads238.8. Tempo and BPM explains why it happens. - Tempo changes.
detect_bpmreturns a single global tempo. A track that speeds up or slows down gets one value for the whole file;detect_beats()returns the beat times if you need to see where the pulse moves. - Many files. Open each with the
withblock, as above, so the decoded samples are released when the loop moves on.
Related
- Music Analysis: BPM, Key and Chord Detection: every analysis call, its options and its result fields.
- Tempo and BPM: how a tempo is estimated from onsets and why it can come out at half or double.
- Detect BPM and Key in the Browser: the same detection in a web page, with the file never leaving the visitor's machine.
- Python Analysis API: the
detect_bpmsignature and its siblings.