Detect BPM and Key in the Browser
To get the tempo and key of a file a visitor picks, decode its bytes with Audio.fromMemoryWithBrowserFallback and call detectBpm() and detectKey() on the result. All of it runs in the page through WebAssembly; the file never leaves the visitor's machine. The function in the Browser tab is the whole job; Node, Python and the CLI do the same from a file path.
import { Audio, init } from '@libraz/libsonare';
await init();
export async function bpmAndKey(file) {
const bytes = new Uint8Array(await file.arrayBuffer());
const audio = await Audio.fromMemoryWithBrowserFallback(bytes);
try {
const key = audio.detectKey();
return { bpm: audio.detectBpm(), key: key.name, confidence: key.confidence };
} finally {
audio.destroy();
}
}import { Audio } from '@libraz/libsonare-native';
const audio = Audio.fromFile('clip.wav');
const key = audio.detectKey();
console.log(audio.detectBpm(), key.name, key.confidence);from libsonare import Audio
with Audio.from_file("clip.wav") as audio:
key = audio.detect_key()
print(audio.detect_bpm(), key.name, key.confidence)sonare bpm clip.wav --json
sonare key clip.wav --jsonPass it the File from an <input type="file"> change event or a drop event. The Node, Python and CLI tabs read a path instead and return the same answer; the CLI's bpm takes no search range, so narrowing it (see below) is a library call. WAV and MP3 are decoded by the engine itself; other formats the browser can play, such as AAC, OGG and FLAC, go through the browser's own decoder, and a stereo file is folded to mono before analysis. destroy() releases the decoded samples, which matters when a visitor drops one file after another.
What you need
- Install:
npm install @libraz/libsonarefor the browser (@libraz/libsonare-nativefor Node), orpip install libsonarefor Python and thesonarecommand. - An audio file: a song or loop with a steady beat, WAV, MP3 or anything the browser decodes.
- To reproduce this page: the clip below is synthetic, so the right answer is known.
Check it on a clip with a known answer
The script writes clip.wav: 16 s of a kick drum on every beat at 120 BPM under the chords C, F, G and C, which puts it in C major. Run it with Node (node make-clip.mjs), then pick clip.wav in your page, or pass it to the Node, Python or CLI tab.
A script that writes the test clip
// Writes clip.wav: 16 s of kick drum and chords, 120 BPM, C major (C, F, G, C).
import { writeFileSync } from 'node:fs';
const sampleRate = 22050;
const bpm = 120;
const beat = 60 / bpm;
const bars = 8;
const x = new Float32Array(Math.round(bars * 4 * beat * sampleRate));
const hz = (midi) => 440 * 2 ** ((midi - 69) / 12);
for (let b = 0; b < bars * 4; b++) {
const start = Math.round(b * beat * sampleRate);
for (let i = 0; i < 0.15 * sampleRate; i++) {
const t = i / sampleRate;
const f = 50 + 80 * Math.exp(-30 * t);
x[start + i] += 0.6 * Math.sin(2 * Math.PI * f * t) * Math.exp(-18 * t);
}
}
const chords = [[60, 64, 67, 48], [65, 69, 72, 53], [67, 71, 74, 55], [60, 64, 67, 48]];
for (let bar = 0; bar < bars; bar++) {
const start = Math.round(bar * 4 * beat * sampleRate);
const length = Math.round(4 * beat * sampleRate);
for (const note of chords[Math.floor(bar / 2)]) {
const f = hz(note);
for (let i = 0; i < length; i++) {
const t = i / sampleRate;
const env = Math.min(1, 20 * t) * Math.exp(-0.6 * t);
const tone = Math.sin(2 * Math.PI * f * t) + 0.5 * Math.sin(4 * Math.PI * f * t);
x[start + i] += 0.08 * env * tone;
}
}
}
const wav = Buffer.alloc(44 + x.length * 2);
wav.write('RIFF', 0);
wav.writeUInt32LE(36 + x.length * 2, 4);
wav.write('WAVEfmt ', 8);
wav.writeUInt32LE(16, 16);
wav.writeUInt16LE(1, 20);
wav.writeUInt16LE(1, 22);
wav.writeUInt32LE(sampleRate, 24);
wav.writeUInt32LE(sampleRate * 2, 28);
wav.writeUInt16LE(2, 32);
wav.writeUInt16LE(16, 34);
wav.write('data', 36);
wav.writeUInt32LE(x.length * 2, 40);
x.forEach((v, i) => wav.writeInt16LE(Math.round(Math.max(-1, Math.min(1, v)) * 32767), 44 + i * 2));
writeFileSync('clip.wav', wav);bpmAndKey and the other tabs return a tempo within 1 BPM of 120 and the key name C major for this clip. The tempo is a measured value, not a rounded one, so it reads a fraction off 120; round it for display.
Reading the answer
- Half or double tempo. A tempo detector can lock onto every other beat, or onto the off-beats in between, and report 60 for a 120 BPM song, or 180 for one at 90. The search runs from 60 to 200 BPM by default. If you know the style, narrow the search with
audio.detectBpm({ bpmMin: 90, bpmMax: 180 }). Tempo and BPM explains why it happens. - Key confidence.
confidenceis the winning key's share against every other candidate key, not a probability that the answer is right. Two keys near 0.5 each usually means a relative major and minor splitting the same evidence. Key Detection shows how to read it, anddetectKeyCandidates()returns the runners-up (sonare key clip.wav --candidates 3on the command line). - Long files. Both calls run synchronously on the thread that calls them. For whole songs, run the same function inside a Web Worker so the page stays responsive; Web Worker Usage has the setup.
The demo ranks the candidate keys behind the winner, with the relative and parallel keys tagged, so you can see how close the runners-up sit.
Related
- Music Analysis: BPM, Key and Chord Detection: every analysis call, its options and its result fields.
- Visual Player: the same detection running live on a file as it plays.
- JavaScript/TypeScript Analysis API: the
detectBpmanddetectKeysignatures.