Detect Chords from an Audio File in JavaScript
To get the chord progression of a file a visitor picks, decode its bytes with Audio.fromMemoryWithBrowserFallback, call detectChords() on the result, and read back a timeline of chord names with start and end times. All of it runs in the page through WebAssembly; the file never leaves the visitor's machine. The Browser tab is the whole job, ending in a list you can render; Node, Python and the CLI read a file path and print the same timeline. For the other detectors (tempo, key, sections, melody) and what each result means, see Music Analysis: BPM, Key and Chord Detection.
import { Audio, init } from '@libraz/libsonare';
await init();
export async function chordTimeline(file, options = {}) {
const bytes = new Uint8Array(await file.arrayBuffer());
const audio = await Audio.fromMemoryWithBrowserFallback(bytes);
try {
return audio.detectChords(options).chords.map((c) => ({
name: c.name,
start: c.startSec,
end: c.endSec,
confidence: c.confidence,
}));
} finally {
audio.destroy();
}
}
const list = document.querySelector('#chords');
document.querySelector('#file').addEventListener('change', async (event) => {
const timeline = await chordTimeline(event.target.files[0]);
list.replaceChildren(
...timeline.map((c) => {
const li = document.createElement('li');
li.textContent = `${c.start.toFixed(1)}s to ${c.end.toFixed(1)}s ${c.name}`;
return li;
}),
);
});import { Audio } from '@libraz/libsonare-native';
const audio = Audio.fromFile('song.wav');
for (const c of audio.detectChords().chords) {
console.log(`${c.startSec.toFixed(1)}s to ${c.endSec.toFixed(1)}s ${c.name}`);
}from libsonare import Audio
with Audio.from_file("song.wav") as audio:
for c in audio.detect_chords().chords:
print(f"{c.start_sec:.1f}s to {c.end_sec:.1f}s {c.name}")sonare chords song.wav
sonare chords song.wav --jsonEach entry is a Chord: name is the symbol (C, Am, G7, Am/C, or N.C. where no chord is clear), startSec and endSec are in seconds, and confidence is how well the chroma fits the chosen chord, from 0 to 1. Chords come back in time order and end where the next begins. WAV and MP3 are decoded by the engine itself; other formats the browser can play 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 clear harmony, 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
This builds 8 s of C, F, G and C, two seconds each, as notes with a few overtones, and passes the samples straight to the request form of detectChords.
A function that builds and analyzes the test clip
import { detectChords, init } from '@libraz/libsonare';
await init();
const sampleRate = 22050;
const chords = [[48, 60, 64, 67], [53, 65, 69, 72], [55, 67, 71, 74], [48, 60, 64, 67]];
const samples = new Float32Array(chords.length * 2 * sampleRate);
chords.forEach((notes, index) => {
for (const midi of notes) {
const hz = 440 * 2 ** ((midi - 69) / 12);
for (let i = 0; i < 2 * sampleRate; i++) {
const t = i / sampleRate;
let tone = 0;
for (let h = 1; h <= 4; h++) tone += Math.sin(2 * Math.PI * hz * h * t) / h;
samples[index * 2 * sampleRate + i] += 0.1 * Math.min(1, 40 * t) * tone;
}
}
});
const result = detectChords({ samples, sampleRate });
console.log(result.chords.map((c) => c.name)); // ['C', 'F', 'G', 'C']The names come back as C, F, G, C in that order, and each chord starts within a beat of where it was written (at 120 BPM, within 0.5 s). The boundaries sit on the detected beat grid, not exactly at 2.0 s, so expect a small offset rather than sample-exact times.
The demo shows the segments the detector returns as blocks on a clip of four triads, with the minimum duration and the triad-only switch to turn.
Options that matter
Pass these as the object given to detectChords(); Python takes the same names in snake_case (use_triads_only, detect_inversions, use_hmm, use_key_context, key_root, key_mode), and the CLI spells them --with-seventh (the opposite of useTriadsOnly), --detect-inversions, --no-hmm, and --key-context with --key-root C --key-mode major. The full list, with defaults, is under Chords in Music Analysis.
| Option | Default | What it changes |
|---|---|---|
useTriadsOnly | true | true searches major, minor, diminished and augmented triads only. false also names seventh and extended chords such as C7 or Cmaj7. |
detectInversions | false | Estimates the lowest note and writes a slash chord such as C/E when it is not the root. |
useHmm | true | Smooths the sequence so chords that follow one another plausibly win over a per-frame decision. |
useKeyContext | false | Biases that smoothing toward a key you pass as keyRoot and keyMode, for example the result of detectKey(). |
const key = audio.detectKey();
const { chords } = audio.detectChords({
useTriadsOnly: false,
detectInversions: true,
useKeyContext: true,
keyRoot: key.root,
keyMode: key.mode,
});Triad, seventh and inversion in plain terms
A triad is the three-note core of a chord: a root, a third and a fifth. C major is C, E and G. A seventh chord adds a fourth note on top, a seventh above the root: C, E, G and B-flat is C7, and C, E, G and B is Cmaj7. An inversion keeps the same notes but puts a different one lowest: E, G, C is still C major, written C/E, "C over E". For a lead sheet the seventh is part of the sound; for a rough harmonic outline the triad is enough and is steadier. Chord Recognition goes into how the templates are matched.
What the detector gets wrong
Measured on synthetic clips with the defaults and then with each switch turned on:
- Seventh chords come back as triads. With
useTriadsOnlyleft attrue, both aC7and aCmaj7are returned asC. PassuseTriadsOnly: falseand they come back asC7andCmaj7. A plain C major triad is stillCwith the full set on. - Inversions are not shown by default. A first-inversion C major triad (E lowest) is returned as
C. WithdetectInversions: trueit isC/E, and a root-position triad staysC. - It labels the harmony, not the band. The result is one chord per stretch of time, chosen from templates. It does not know which instrument played which note.
- Chord times follow the beat grid. By default the detector decides on detected beats, so boundaries land on the grid rather than at the exact instant the sound changes. Pass
useBeatSync: falsefor frame-level boundaries. - Real recordings are harder than this clip. The clip has no drums, vocals or noise. Chord Recognition lists the usual confusions; treat the timeline as a draft to check by ear.
Like the other analysis calls, detectChords() runs synchronously on the thread that calls it. For whole songs, run the same function inside a Web Worker so the page stays responsive; Web Worker Usage has the setup.
Related
- Music Analysis: BPM, Key and Chord Detection: every analysis call, its options and its result fields.
- Detect BPM and Key in the Browser: the tempo and key calls this page's
useKeyContextoption reads from. - Visual Player: chord detection running live on a file as it plays.
- JavaScript/TypeScript Analysis API: the
detectChordssignature.