Three.js Beat Detection (Onset Detection & Tempo Estimation)

Real-time beat detection in Three.js, comparing each frame's band energy from a Web Audio drum machine against a running average to detect onsets, with pulsing geometry, an energy history graph and tempo estimated from inter-onset intervals.

Key topics: beat detection, onset detection, tempo estimation, web audio api, audio reactive, three.js music visualization

What this code does

- Band Energy: the FFT spectrum is averaged over a band (kick 40–150 Hz, snare 180–2000 Hz or hats 5–14 kHz) and squared.
- Adaptive Threshold: an onset fires when energy exceeds k × its ~1 s running mean (yellow line), with a 180 ms refractory gap.
- Tempo: 60 / median inter-onset interval, folded into 70–180 BPM to resolve half- and double-time ambiguity.
- Patterns: compare four-on-the-floor (easy) with breakbeats and syncopation, where kick spacing varies.
- Visuals: the core and rings pulse on detections, and a log-frequency spectrum ring surrounds them.
- Controls: pattern, tempo, detection band, sensitivity and bass line; press Play sound to hear it.

Continue Learning

JavaScript Implementation

ES6+
// Energy onset detection: compare this frame's band energy with a running average
const history = []

function detect (freqDb) {
  const e = bandEnergy(freqDb, 40, 150) ** 2            // kick-drum band
  history.push(e); if (history.length > 45) history.shift() // ≈ 0.75 s at 60 fps
  const mean = history.reduce((a, b) => a + b) / history.length
  if (e > mean * 1.45 && performance.now() - last > 180) { last = performance.now(); onBeat() }
}
// Tempo ≈ 60 / median(inter-onset interval), folded into 70–180 BPM