Audio-Reactive From Zero · Episode 03

Beat Detection

Beat Detection is Episode 03 of Audio-Reactive From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 03 · Audio-Reactive From Zero

There's a line between visuals that hit on the drop and visuals that just wobble vaguely in time with the music. Cross it, and your work suddenly looks intentional — every kick lands a punch, every snare flicks a light, the whole frame breathes on the grid the track is built on. Stay on the wrong side of it and you get the thing everyone has seen a thousand times: a blob that gently pulses, technically "reacting," but never actually on the beat. The difference is one small function that answers a single yes/no question sixty times a second: is a beat happening right now?

This episode builds that function from nothing. We take the bass energy out of the spectrum, compare it against its own recent average, fire when it spikes past an adaptive threshold, and add a short refractory window so a single kick counts as exactly one beat — not five. Then we wire that boolean into a pulse envelope and watch a shape punch on every beat. By the end you'll have a beat detector you can drop into anything, and a clear feel for why a fixed threshold could never have worked. The demo is alive the moment it loads — its synthetic track has a clean ~128 BPM kick, so there's a real pulse to find before you ever turn the sound on.

0 fps
synthetic ~128 BPM track — watch the kick land
synthetic — click to hear the synth
Web Audio · synthetic
Live bass energy as a moving bar. This is the raw signal every beat detector starts from.

What you're looking at

One machine, six views of it. The same numbers flow through every stage — what changes is how much of the detector is switched on and how it's drawn. Step the stage selector to watch a raw energy bar grow, one decision at a time, into a clean beat-driven pulse.

  • Stage 1 — Bass energy. A single bar showing the instantaneous energy in the bass band. It leaps on every kick. This is the only input the detector ever sees.
  • Stage 2 — Running average. We overlay the rolling average that the energy hovers around. The threshold is going to ride on this, not on a fixed line — that's the whole trick.
  • Stage 3 — Threshold → beat flag. Flash whenever energy crosses average × sensitivity. It works… but it's flickery: one kick can trip the flag several frames in a row.
  • Stage 4 — Refractory window. Ignore any beat that lands within a few milliseconds of the last. Now one kick = one clean beat. The flicker is gone.
  • Stage 5 — Pulse on beat. The boolean drives a decay envelope: set it to 1 on a beat, fade it each frame. A shape scales and flashes, then settles — until the next hit.
  • Stage 6 — Choreography. Beat-driven elements (punch) next to sustained, band-driven elements (a smooth glow following the chosen band) — plus a live beat counter. This is what "reacting to music" actually looks like.

The controls map straight onto concepts. sensitivity is the multiplier on the average — higher means fewer, surer beats. refractory is the minimum gap in milliseconds between two beats. band picks which slice of the spectrum we measure: bass for kicks, mid for snares, treble for hats. And enable sound swaps the synthetic spectrum for a real AnalyserNode reading a looping synth (or your mic / a file), so you can point the same detector at actual audio.

Stage 1 — Bass energy is the only signal

A beat — a kick drum especially — is a sudden burst of low-frequency energy. So before anything clever, we need one number per frame: how much energy is in the bass right now. The spectrum is an array of magnitudes, index 0 = lowest frequency. We take the bottom slice, square each magnitude (energy is amplitude squared — squaring also makes spikes spikier), and average.

That single bar in Stage 1 is the entire raw input. Everything else in this episode is decisions about this number. Notice it doesn't sit still even between kicks — there's bass bleed, room noise, the synth's sustained low end. A naive "fire when energy is high" would trip constantly. We need a sense of what "high" means relative to the recent past.

Stage 2 — The running average is the moving goalpost

Here's the central idea of the whole episode, and it's worth saying plainly: a fixed threshold cannot work. Set it low and a loud track triggers on every frame; set it high and a quiet track never triggers at all. The same song gets louder in the chorus and the threshold you tuned for the verse is suddenly wrong.

The fix is to compare the current energy not against a constant, but against its own recent average. We keep the last ~0.7 seconds of energy values in a small history buffer and average them every frame. In Stage 2 that average is the second, calmer line riding under the spiky energy bar. A beat is then simply: energy that pokes well above its own recent average. Loud track, quiet track — doesn't matter, because the goalpost moves with the music.

Stage 3 — Threshold gives you beats (and false positives)

Now we draw the threshold line at average × sensitivity and flash the frame whenever energy crosses it. Suddenly there are beats! On the synthetic track the flash lands right on the kick. Drag sensitivity down toward 1.05 and watch the detector get trigger-happy; push it toward 2.0 and it only fires on the hardest hits.

But look closely (it helps to lower sensitivity): a single kick often flashes for several frames in a row. The energy spike isn't one frame wide — it ramps up and decays over ~100ms, and it's above threshold the whole way up and partway down. If you were counting beats here, you'd massively over-count. This is the classic false-positive problem, and it's not solved by tuning sensitivity — it's solved by time.

Stage 4 — A refractory window: one kick, one beat

Borrow a word from neuroscience: after a neuron fires it has a refractory period where it physically cannot fire again. We give our detector the same thing. The moment a beat fires, we stamp the time and refuse to fire again until at least refractory milliseconds have passed. At 128 BPM beats are ~470ms apart, so a window of ~120ms is comfortably shorter than a real beat gap but far longer than a single spike's multi-frame ramp.

Flip to Stage 4 and the flicker collapses into crisp, single flashes — one per kick. Drag the refractory slider up and you'll eventually start missing real beats (the window swallows them); drag it too low and the flicker creeps back. The sweet spot is "longer than one spike, shorter than one beat." This one timer is the difference between a detector that's usable and one that's noise.

Stage 5 — A pulse envelope turns a boolean into motion

A beat is an instant — a single true on one frame. But motion needs duration: a punch that's visible for one 16ms frame is invisible. So we convert the instant into a decaying envelope. Keep a value pulse in [0,1]. On a beat, slam it to 1. Every frame, multiply it by a decay factor so it falls smoothly back toward 0. Drive a shape's scale and brightness from pulse and you get a satisfying thump that blooms and settles, ready for the next hit.

The refractory slider doubles as a decay control here (longer setting = slower, more lingering decay), so you can dial the pulse from a sharp tick to a slow swell. This envelope is the single most reused idea in reactive visuals: any "react and relax" behavior — flashes, kicks, shakes, color pops — is a value set on an event and decayed every frame.

Stage 6 — Choreography: beats and bands together

Real music-reactive work layers two kinds of motion. Discrete elements fire on beats (the pulse from Stage 5). Continuous elements follow a sustained quantity — the smoothed energy of a frequency band — and glide rather than punch. Stage 6 shows both: a central shape that punches on every detected beat, surrounded by a ring that swells continuously with the selected band's energy, plus a running beat counter ticking up with each hit.

Switch the band selector and the continuous ring re-tunes to bass, mid, or treble while the punch keeps tracking whatever band you're detecting on. That split — something that hits on the grid, something that flows underneath it — is the grammar of nearly every great audio visual. Episode 04 expands the "continuous" half into a full bass/mid/treble mapping; today we've nailed the "discrete" half: the beat.

How the code works

Four small pieces, and you have the whole thing. First, detectBeat: measure energy in a frequency band, push it into a fixed-length history, average that history, and return whether the current energy clears average × sensitivity — plus an absolute floor so silence never triggers.

// (a) Beat detection: band energy vs its own running average
let energyHist = [];                         // ~0.7s of recent energy

function bandRange(N, band) {              // which spectrum bins to sum
  if (band === 'bass')   return [0,                  Math.floor(N * 0.12)];
  if (band === 'mid')    return [Math.floor(N * 0.12), Math.floor(N * 0.45)];
  return [Math.floor(N * 0.45), N];                          // treble
}

function detectBeat(spectrum, band, sensitivity) {
  const [lo, hi] = bandRange(spectrum.length, band);
  let e = 0;
  for (let i = lo; i < hi; i++) e += spectrum[i] * spectrum[i];  // energy = amplitude²
  e /= (hi - lo);

  energyHist.push(e);
  if (energyHist.length > 43) energyHist.shift();        // ~43 frames ≈ 0.7s @60fps
  const avg = energyHist.reduce((a, b) => a + b, 0) / energyHist.length;

  const floor = 600;                              // energy floor: silence ≠ beat
  return { hit: e > avg * sensitivity && e > floor, energy: e, avg };
}

That function alone is Stage 3 — correct, but it'll fire several frames per kick. The fix is a refractory timer: remember when we last fired and reject any hit that arrives too soon. This is the entire difference between Stage 3 and Stage 4.

// (b) Refractory window: collapse a multi-frame spike into one beat
let lastBeatMs = -1e9;                         // time of the last accepted beat

function acceptBeat(rawHit, nowMs, refractoryMs) {
  if (rawHit && nowMs - lastBeatMs >= refractoryMs) {
    lastBeatMs = nowMs;                          // stamp it; the window starts now
    return true;                                // a real, de-duplicated beat
  }
  return false;
}

Next, the pulse envelope that turns that one-frame boolean into visible motion: snap to 1 on a beat, decay toward 0 every frame. The decay is computed per-second so it's frame-rate independent.

// (c) Pulse envelope: set to 1 on beat, decay each frame
let pulse = 0;

function updatePulse(beat, dt, halfLifeMs) {
  if (beat) pulse = 1;                          // the punch
  // exponential decay: lose half the value every halfLifeMs
  const k = Math.pow(0.5, (dt * 1000) / halfLifeMs);
  pulse *= k;                                    // the relax
  return pulse;
}

Finally, wire beat → visual punch in the frame loop. Read audio into the shared arrays, detect, de-dup, decay, draw. The shape's size and brightness are just a base plus pulse.

// (d) Per frame: detect → refractory → envelope → draw
function frame(now) {
  const dt = (now - prev) / 1000; prev = now;
  readAudio(now / 1000);                       // fills spectrum[] (synth or analyser)

  const { hit } = detectBeat(spectrum, band, sensitivity);
  const beat = acceptBeat(hit, now, refractoryMs);
  if (beat) beatCount++;
  const p = updatePulse(beat, dt, halfLifeMs);

  const r = baseR * (1 + 0.6 * p);            // scale with the envelope
  ctx.fillStyle = `rgba(56,189,248,${0.3 + 0.7 * p})`;
  ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.fill();

  requestAnimationFrame(frame);
}

That's a complete, production-usable beat detector in four short blocks. The same detectBeat / acceptBeat / updatePulse trio drives every stage in the demo above; only the drawing changes.

Common pitfalls

  • A fixed threshold fails on quiet or loud tracks. The single most common mistake. if (energy > 50) beat() works on exactly one song at one volume. Always compare against a running average so the threshold tracks the track. This is the entire reason Stage 2 exists.
  • False positives from one kick. A bass spike spans many frames, so a bare threshold fires repeatedly per hit. Without a refractory window your beat count and your visuals will both stutter. ~100–150ms is a good default for most music; it's well under one beat at typical tempos.
  • Detecting on the wrong band. Kicks live in the bass (bottom ~12% of bins). Run beat detection on the full spectrum and busy mids/treble will smear your average and bury the kick. Pick the band that carries the pulse you want — bass for four-on-the-floor, mid for a snare-driven groove.
  • No energy floor, so silence "beats." When a track is near silent, the average drops to almost nothing — and then any faint noise is "well above average" and trips the detector. An absolute floor (e > 600 above) means silence stays silent. Tune it to your signal's scale.
  • Smoothing hides the spike. The analyser's smoothingTimeConstant is great for pretty bars but it flattens the sharp onsets beats depend on. If detection feels mushy, lower it (or run detection off a less-smoothed copy of the spectrum).

Exercises

  1. Estimate BPM. Record the timestamp of each accepted beat, take the intervals between consecutive beats, and report 60000 / medianInterval as beats-per-minute. Use the median (not the mean) so a single missed or doubled beat doesn't wreck the estimate. Display it next to the beat counter — it should read ~128 on the synthetic track.
  2. Detect the snare separately. Run a second detectBeat on the mid band with its own history and its own refractory timer. Now you have two independent triggers, kick and snare. (You'll need a second energyHist and a second lastBeatMs — shared globals would cross the streams.)
  3. Trigger different visuals per band. Wire kick → a screen-wide flash, snare → a horizontal shake, hat → a sparkle of particles. Three detectors, three envelopes, three behaviors. This is the seed of a real VJ rig — and a perfect setup for the per-band mapping in Episode 04.

What's next

Episode 04 — Frequency Bands. Beat detection answered a yes/no question off one band. Next we use all the bands at once: split the spectrum into bass, mid, and treble and map each to a different visual parameter — bass drives scale, mids drive color, treble drives detail — so the whole frame moves as a coordinated response to the music's full texture. The discrete punch you built today plus the continuous, multi-band flow of next episode is the complete reactive toolkit.