Audio-Reactive From Zero · Episode 04

Frequency Bands

Frequency Bands is Episode 04 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 04 · Audio-Reactive From Zero

Wire a single number — "how loud is the music right now" — to one shape and it twitches. It reacts, technically, but it reads as noise: the whole thing inflates and deflates with no relationship to anything you can hum. The eye sees motion and the ear hears a song, and the two never line up. That gap is why most first audio-reactive sketches feel dead even though they're clearly "working."

The fix is the most important idea in this entire series, and it's almost embarrassingly simple: music is not one number, it's a spectrum. Split that spectrum into bass, mid, and treble, and drive a different visual parameter from each — bass makes the shape pump, mid makes it spin, treble makes it glow. Now the kick has a job, the melody has a job, the hi-hats have a job, and a single shape suddenly feels like it's dancing instead of vibrating. Picking which band drives which parameter is the whole art. Let's build it.

0 fps
click 🔊 enable sound — or just watch, it's already alive
synthetic — no audio needed
Web Audio · synthetic
Three bars: bass (20–250 Hz), mid (250 Hz–4 kHz), treble (4–16 kHz). Watch which one moves with what you hear.

What you're looking at

That demo is alive right now, with no microphone, no audio file, and no click. It's driven by a synthetic spectrum — a procedurally generated fake of a ~128 BPM track, with a kick on the bass, a wandering melody in the mids, and sparkle up top. Everything you build in this series reads from two plain arrays (spectrum and waveform), so it animates identically whether those arrays are filled by a fake or by a real AnalyserNode. Hit 🔊 enable to swap in a real looping synth (or your mic) and hear the thing you're watching — but you never need to.

The six stages are six views of one machine. Stage 1 just meters the three bands so you can see them move independently. Stages 2–4 each wire one band to one parameter so you can feel the mapping in isolation. Stage 5 is the payoff: all three at once on a single shape. Stage 6 spreads the three bands across three different elements of a little scene. The four sliders let you move the band boundaries, change how hard each band is smoothed, and dial the overall mapping strength from "dead still" to "too much."

Stage 1 — The three bands

Before mapping anything to a shape, you have to see that the bands are genuinely different signals. Three bars: bass, mid, treble, each one the average magnitude of its slice of the spectrum, labeled with its rough frequency range. Watch them as the synthetic track plays: the bass bar slams on every kick, the mid bar wanders with the melody, the treble bar shimmers. They are not the same number scaled three ways — they rise and fall on their own schedules. That independence is the entire reason this technique works. Drag the two edge sliders and watch the bars redraw: you're literally choosing where one band ends and the next begins.

Stage 2 — Bass → scale

Now one wire. The bass band drives the scale of a single shape: loud low end → big shape, quiet → small. This is the most satisfying single mapping in audio-reactive work because it's exactly what your body already does at a show — you feel the kick in your chest, and here the shape pumps with it. Note how discrete it feels: each kick is a punch, then a settle. Turn the smoothing slider down to 0 and it gets twitchy and harsh; turn it up and the pumps get fat and lazy. The map intensity slider scales how much a full-bass moment grows the shape.

Stage 3 — Mid → rotation

Swap the wire. Now the mid band — where melody and most instruments live — drives rotation. The louder the mids, the faster the shape spins. Because mids are busier and more continuous than the kick, rotation feels fluid rather than punchy: the shape surges and eases as the melody moves. This is a deliberate pairing — a continuous-ish band mapped to a continuous parameter. (Map the kick to rotation instead and you'd get a strobe-like stutter; map the mids to scale and you'd get a shape that never sits still. Right band, right parameter.)

Stage 4 — Treble → color

The third wire. Treble — hi-hats, cymbals, sibilance, "air" — drives hue. Quiet top end sits at one color; a burst of sparkle shoves the hue around the wheel. Treble is the twitchiest band, so it's a great match for color: a flickering hue reads as energy and shimmer, whereas a flickering size would just read as a glitch. We map the band to hue in an HSL color and let saturation/lightness ride along too, so loud treble doesn't just shift the color, it makes it brighter and more vivid.

Stage 5 — All three

The payoff. One shape, three independent wires at once: bass→scale, mid→rotation, treble→color. Nothing here is new — it's literally Stages 2, 3, and 4 composed on the same object — but the combination is what makes it feel alive. The kick pumps it, the melody spins it, the hats color it, and because each motion tracks a different part of the music, your brain stops seeing "a reacting shape" and starts seeing "a thing that is dancing to this song." Toggle the map intensity down to ~0.3 for a tasteful version, up to 2 for a music-video version.

Stage 6 — A scene

The same idea, spread across an arrangement instead of stacked on one shape. Bass drives a pulsing core, mid drives a spinning ring around it, and treble spits out sparks. Each element has exactly one job, tied to exactly one band, and the result is a tiny composition that breathes with the track. This is the move you'll reach for constantly: instead of cramming every reaction onto one object, give each band its own thing to own. Assigning bands deliberately — not reacting to everything with everything — is what separates a music visualizer from visual mush.

How the code works

Everything below reads from one Uint8Array called spectrum — index 0 is the lowest frequency, the last index is the highest, values are 0..255. (Episode 01 covered where that array comes from; here we only consume it.) The pipeline is four small steps: average the spectrum into three bands, smooth each band, map a band to a transform and to a color, then compose all three on one shape.

1 · Averaging the spectrum into bass / mid / treble (log-aware)

A band is just the average of a contiguous slice of bins, normalized to 0..1. The one trap: the boundaries must be chosen on a logarithmic idea of pitch, not a linear one. In a 256-bin spectrum, "bass" is only the first handful of bins — everything an ear calls bass is crammed into the bottom few percent. If you naïvely split the array into equal thirds, your "bass" band would swallow most of the melody and the kick would barely register. So we express the edges as fractions of the spectrum and keep bass tiny:

// edgeLo ≈ 0.08 (bass│mid), edgeHi ≈ 0.5 (mid│treble) — fractions, not bin counts.
// Bass is deliberately a thin sliver of low bins; treble is the wide top half.
function bandAverage(spectrum, fromFrac, toFrac) {
  const N = spectrum.length;
  const lo = Math.floor(fromFrac * N);
  const hi = Math.max(lo + 1, Math.floor(toFrac * N));   // always ≥1 bin wide
  let sum = 0;
  for (let i = lo; i < hi; i++) sum += spectrum[i];
  return (sum / (hi - lo)) / 255;            // → 0..1, ready to map
}

const bass   = bandAverage(spectrum, 0,       edgeLo); // the kick
const mid    = bandAverage(spectrum, edgeLo,  edgeHi); // melody / body
const treble = bandAverage(spectrum, edgeHi,  1);      // hats / air

Returning 0..1 from this function is doing real work: every downstream mapping can assume a clean normalized input, so a "loud bass" is always ~1 no matter the bin count or how you moved the sliders. Normalize once, here, and you never fight raw 0..255 values again.

2 · Smoothing each band (lerp)

Raw band averages are jumpy — one noisy frame and the shape strobes. The cure is a one-line low-pass filter: each frame, move the smoothed value a fraction of the way toward the new reading (a lerp, a.k.a. an exponential moving average). Keep a separate smoothed value per band, because they have different rhythms — you often want the bass snappier (less smoothing) and the treble calmer (more):

// One smoothed value PER band. `smooth` = 0 (instant) .. 0.95 (very laggy).
const sm = { bass: 0, mid: 0, treble: 0 };

function smoothBand(prev, next, smooth) {
  // lerp: blend `smooth` of the old value with (1-smooth) of the new one.
  return prev * smooth + next * (1 - smooth);
}

sm.bass   = smoothBand(sm.bass,   bass,   smooth);
sm.mid    = smoothBand(sm.mid,    mid,    smooth);
sm.treble = smoothBand(sm.treble, treble, smooth);

This is the single biggest "make it feel good" knob in the demo. Too little smoothing and everything jitters; too much and the visual lags so far behind the beat it feels disconnected. Around 0.8 is a good default for 60 fps — and note the analyser itself has its own smoothingTimeConstant, so in a live setup you're smoothing twice. That's fine; they stack.

3 · Mapping a band → a transform, and a band → a color

A normalized band value is just a number in 0..1. Mapping it to a visual means choosing a range for the target parameter and interpolating across it. Scale and rotation are linear ranges; color is an HSL where we push the band into the hue (and let it brighten saturation/lightness so loud = vivid):

// band (0..1) → a SCALE multiplier. Base 1.0, grows up to +0.8 at full bass.
function bandToScale(v, intensity) {
  return 1 + v * 0.8 * intensity;        // 1.0 (silent) .. 1.8 (slammed)
}

// band (0..1) → ROTATION SPEED (radians/frame). Louder mids = faster spin.
function bandToSpin(v, intensity) {
  return v * 0.06 * intensity;            // accumulate into an angle each frame
}

// band (0..1) → an HSL color string. Treble pushes hue around the wheel.
function bandToColor(v, intensity) {
  const hue = (180 + v * 200 * intensity) % 360;  // cyan → magenta as it rises
  const sat = 60 + v * 40 * intensity;              // louder = more saturated
  const light = 45 + v * 25 * intensity;            // louder = brighter
  return `hsl(${hue}, ${sat}%, ${light}%)`;
}

The art is entirely in those constants and which band you feed in. The intensity slider multiplies the reactive part of every mapping while leaving the base alone — so at intensity = 0 the shape is a calm default (scale 1, no spin, the base hue) and at 2 it's slammed. That base/reactive split is the pattern: a steady resting value plus an audio-driven offset.

4 · Composing the three mappings on one shape

With three smoothed bands and three mapping functions, the payoff stage is just applying all of them to one object — scale from bass, an accumulating rotation from mid, fill color from treble. Note the rotation accumulates (a speed integrated into an angle), while scale and color are set absolutely from the current band:

let angle = 0;                                  // persists across frames

function drawPayoff(ctx, cx, cy, sm, intensity) {
  angle += bandToSpin(sm.mid, intensity);        // MID → rotation (integrate)
  const scale = bandToScale(sm.bass, intensity);  // BASS → scale (absolute)
  const fill  = bandToColor(sm.treble, intensity); // TREBLE → hue (absolute)

  ctx.save();
  ctx.translate(cx, cy);
  ctx.rotate(angle);
  ctx.scale(scale, scale);
  ctx.fillStyle = fill;
  drawShape(ctx);                              // a square, a poly, whatever
  ctx.restore();
}

That's the whole technique. Three numbers, three wires, one shape. Everything fancier — particle systems, 3D, shaders — is this same skeleton with a richer drawShape.

Common pitfalls

  • Linear band boundaries. Splitting the spectrum into three equal slices makes "bass" eat the whole song. Pitch is logarithmic — an octave is a doubling of frequency — so bass is only the lowest few percent of bins. Keep the bass band a thin sliver (here, edges at fractions like 0.08 and 0.5, not 0.33 and 0.66). For a "musical" bar layout you can go further and space the boundaries on a true log curve.
  • No per-band smoothing → strobing. Raw FFT frames are noisy; map them straight to a transform and the shape vibrates instead of dances. Smooth each band with its own lerp. And smooth them separately — averaging them together first throws away the very independence you split them for.
  • Over-mapping (everything reacts to everything). The most common beginner mistake: wiring bass and mid and treble all into scale, rotation, and color at once. The result is mush — every parameter twitches on every sound and nothing reads. Assign deliberately: one band owns one parameter. Less wiring, more legibility.
  • Forgetting to normalize. If your band values are raw 0..255, every mapping constant has to be re-tuned per band and per source, and a quiet track barely moves anything. Normalize each band to 0..1 at the source (divide by 255), and every downstream mapping becomes source-independent.
  • Mapping the kick to a continuous parameter. Bass is punchy; rotation and hue are continuous. Drive rotation from the kick and you get a stutter, not a spin. Match the band's character to the parameter's: punchy band → punchy parameter (scale), continuous band → continuous parameter (rotation/color).

Exercises

  1. Add a fourth band — "air" / brilliance. Split the treble in two: keep mid│treble where it is, add a third edge around 0.8, and make everything above it an air band. Wire it to something subtle — glow radius, or a faint outline opacity — so the very top of the spectrum (cymbal shimmer, sibilance) has its own quiet job. Four bands is the sweet spot for a lot of real visualizers.
  2. Swap the mappings live. Add a control that re-routes which band drives which parameter (bass→color, treble→scale, etc.). Run the demo and feel how wrong the "bad" pairings are — kick-on-rotation stutters, hats-on-scale jitters. Experiencing the bad mappings is the fastest way to internalize why the defaults are the defaults.
  3. Drive a particle emitter with bass. Each frame, if sm.bass crosses a threshold, spawn a burst of particles from the center (velocity proportional to the band value). The kick now throws sparks instead of just resizing a shape — the seed of Stage 6's scene, and a preview of the particle work later in the series.

What's next

Episode 05 — The Waveform: Oscilloscope and Audio Lissajous. So far we've lived entirely in the frequency domain — how much of each pitch. Next we switch to the time domain and draw the raw waveform itself: a glowing oscilloscope trace, then the hypnotic looping curves of an audio Lissajous figure. Same two-array data model, a completely different and gorgeous way to see sound.