Audio-Reactive From Zero · Episode 02
The Bar Visualizer
The Bar Visualizer is Episode 02 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 .
You have drawn FFT bars before. Everyone has. You grab
getByteFrequencyData, loop over the array, draw a rectangle per value,
and… it looks off. A wall of stubby bars on the left thrashing like crazy,
and three-quarters of the screen on the right sitting flat and dead no matter how
bright the track is. It does not look like the visualizers you remember from Winamp
or a club VJ rig. It looks like a buggy spreadsheet.
The fix is two ideas, and almost nobody applies them: log-frequency binning (so the bars are spaced the way your ears hear pitch, not the way the FFT happens to index its array) and temporal smoothing (so the bars glide instead of jitter). Add a gradient, rounded caps, a mirror, and a polar layout, and the same boring array becomes the shareable, genuinely musical thing in your feed. This episode builds it in six stages — a polished linear visualizer and a radial one — from one shared spectrum array, alive on first paint, with zero dependencies.
What you’re looking at
One canvas, one spectrum array of 0..255 frequency
magnitudes (index 0 is bass, the last index is treble), redrawn sixty times a second.
Before you click anything, that array is filled by a tiny synthesizer that fakes a
128-BPM track — a kick on every beat, a melodic mid swell, treble sparkle — so the
demo is alive on first paint with no audio at all. Click enable
sound and, on that user gesture, we spin up a real AudioContext,
play a looping synth, and feed an AnalyserNode into the exact same array.
Every visual reads from that one array and nothing else, so the synthetic and live
paths are pixel-identical in behaviour.
Step the stage dropdown through all six and watch the same data go from "buggy spreadsheet" to "club rig." The scale toggle (log vs linear) is the single most important control on the page — flip it on any stage and you will feel why this episode exists. bins changes how many bars we draw; smoothing sets how lazily they chase their targets.
Stage 1 — Naive linear bars
The version everybody writes first. We have, say, 512 frequency bins from the analyser. We want 64 bars. So we just chop the array into 64 equal slices and average each slice: bar 0 is bins 0–7, bar 1 is bins 8–15, and so on, straight across. Draw a rectangle per bar, height proportional to the average. Done.
And it looks wrong, in a very specific way. All the action is jammed into
the left quarter and the right three-quarters barely twitch. That is not a
bug — it is physics meeting human hearing. An FFT spaces its bins
linearly in Hz: if the top bin is ~22 kHz across 512 bins, each bin is
about 43 Hz wide. But musically interesting energy — the kick, the bass, the
vocal fundamentals, most of a piano — lives below ~1 kHz, which is only the first
~23 bins. The entire bottom two octaves of a song are crammed into the leftmost
handful of bars, while the top half of the screen is spread thin across frequencies
that, in most music, carry almost nothing but air and cymbals. Flip the
scale control to linear on any later stage to summon
this problem back at will.
Stage 2 — Log-frequency bins
Here is the fix, and it is the whole episode in one idea. Your ears hear pitch logarithmically. Going up one octave means doubling the frequency — 110 Hz → 220 Hz → 440 Hz → 880 Hz. Those are equal musical steps but wildly unequal in Hz (110, then 220, then 440 apart). A visualizer that looks musical must give each octave roughly equal screen width, not each kilohertz.
So instead of slicing the bin array evenly, we slice it geometrically: bar
i covers a frequency range whose edges grow by a constant ratio. The
first bars map to a tiny span of low bins; the last bars each swallow a wide span of
high bins (averaged together). Now bass gets its fair share of bars, the mids breathe,
and the treble — which used to be 75% dead pixels — collapses into a few lively bars at
the right. The same track suddenly looks like music. This single change is the
number-one reason home-made visualizers go from amateur to pro.
Stage 3 — Smoothing
Now the bars look balanced, but they jitter. Raw FFT output is noisy frame
to frame, so each bar flickers and twitches even on a steady note. The cure is
temporal smoothing: don’t snap a bar to its new value, ease it toward
the value. Keep a "displayed height" per bar and each frame move it a fraction of the
way to the fresh target — a classic lerp. A smoothing of 0 means
"snap instantly" (jittery); 0.9 means "crawl" (smooth but laggy). The
sweet spot is usually 0.6–0.8. Drag the smoothing slider
on this stage and watch the bars go from twitchy to liquid.
(The analyser has a built-in smoothingTimeConstant that does something
similar to the bins before you read them. We do our own lerp on the
displayed bars instead, because it works identically for the synthetic path,
it survives bin re-grouping, and it gives you one knob you fully control. Use one or
the other — stacking both just doubles the lag.)
Stage 4 — Styling
Same data, now dressed up. Three touches turn a bar chart into a visualizer: a vertical gradient fill (cool at the base, hot at the tip) so tall bars glow; rounded caps so the bars read as soft objects instead of spreadsheet cells; and a mirror — draw each bar both up and down from a centre line so the whole thing is symmetric and twice as punchy. We also add peak-hold caps: a thin marker that jumps to each bar’s highest recent value and then sags slowly, so transients leave a visible trail. Use the style dropdown to toggle between flat bars, gradient, and the full mirror-plus-caps treatment.
Stage 5 — Circular / radial
The shape that reads as "music video." Instead of laying bars left-to-right, lay
them around a circle: bar i sits at angle i / count × 2π, and
its height grows outward from a base radius. Bass at the top, sweeping
clockwise through the spectrum and back. The maths is two lines of trig per bar — a
base point on the inner circle and a tip point further out along the same angle — but
the result feels like an entirely different, far fancier visualizer. It is the same
array.
Stage 6 — Polished combo
Everything at once: the radial layout, mirrored into a full ring, filled with a hue palette that runs around the circle, smoothed so it breathes, with peak caps riding the transients and a soft glow on the kick. This is the frame you would actually post. Nothing here is new — it is stages 2 through 5 stacked. That is the lesson of the whole episode: the polish is not one clever trick, it is a handful of cheap, well-known ideas applied on top of correctly binned, smoothed data.
How the code works
The through-line of this whole series is one array. We allocate it once and refill it every frame — from the synth before you click, from the analyser after:
// One shared array is the entire data model (index 0 = bass).
const N = 512;
const spectrum = new Uint8Array(N);
const waveform = new Uint8Array(N);
function readAudio(t) {
if (usingReal && analyser) {
analyser.getByteFrequencyData(srcFreq); // live bins
resampleInto(srcFreq, spectrum); // → our N
} else {
synthAudio(t, spectrum, waveform); // alive with no audio
}
}
(a) Log bin grouping — the musical fix
This is the function that earns the episode. We want count bars. For
each bar we compute the slice of the spectrum array it owns. In linear
mode that slice is a fixed width; in log mode the slice boundaries
grow geometrically, so each bar covers roughly one constant musical interval. We
average the bins inside the slice (always taking at least one) so no bar is empty:
// Map bar i → a frequency-bin range, average those bins → one bar value.
function groupBars(spectrum, count, useLog, out) {
const N = spectrum.length;
const minBin = 1; // skip DC / bin 0 (it's junk)
for (let i = 0; i < count; i++) {
let lo, hi;
if (useLog) {
// geometric edges: each bar spans a constant *ratio* of Hz
lo = Math.floor(minBin * Math.pow(N / minBin, i / count));
hi = Math.floor(minBin * Math.pow(N / minBin, (i + 1) / count));
} else {
lo = Math.floor(i / count * N); // even slices = bass-crammed
hi = Math.floor((i + 1) / count * N);
}
if (hi <= lo) hi = lo + 1; // never an empty bar
let sum = 0;
for (let b = lo; b < hi && b < N; b++) sum += spectrum[b];
out[i] = sum / (hi - lo) / 255; // 0..1
}
}
That Math.pow(N/minBin, i/count) is the entire trick. It is the
inverse of "take the log of the frequency": equal steps in i become equal
ratios in bin index, which is equal octaves to your ear.
(b) Smoothing lerp — kill the jitter
Keep a persistent disp[] array of what is currently drawn. Each frame,
glide it toward the fresh targets. One line, and the difference between "twitchy" and
"liquid":
// smooth ∈ [0,1): 0 = snap instantly, 0.9 = slow crawl.
function smoothToward(disp, target, smooth) {
const a = 1 - smooth; // lerp factor per frame
for (let i = 0; i < disp.length; i++) {
disp[i] += (target[i] - disp[i]) * a; // move a fraction of the way
}
}
Optionally let bars fall slower than they rise — music feels punchier when
hits snap up but decay gently. You get that for free by using a bigger
smooth only when target < disp.
(c) The circular / polar layout
Polar is just "where do I put bar i, and which way is up?" The angle is
its index around the circle; "up" is radially outward. We draw a thick line from a
point on the inner radius to a point further out along the same angle:
// Lay `count` bars around a circle, growing outward from r0.
function drawRadial(ctx, disp, count, cx, cy, r0, maxLen) {
ctx.lineCap = 'round';
for (let i = 0; i < count; i++) {
const ang = (i / count) * Math.PI * 2 - Math.PI / 2; // bass at top
const len = disp[i] * maxLen;
const ca = Math.cos(ang), sa = Math.sin(ang);
const x0 = cx + ca * r0, y0 = cy + sa * r0; // inner base
const x1 = cx + ca * (r0 + len), y1 = cy + sa * (r0 + len); // outer tip
ctx.strokeStyle = `hsl(${i / count * 320}, 90%, ${50 + len * 40}%)`;
ctx.lineWidth = 2 + (Math.PI * 2 * r0 / count) * 0.6; // fit the arc
ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1, y1); ctx.stroke();
}
}
To mirror it into a full ring (Exercise 2), draw a second bar at
ang + π, or only sweep half the circle and reflect — either gives you the
symmetric look in Stage 6.
(d) Gradient fill + rounded caps
For the linear stages, a per-bar vertical gradient and a rounded top do most of the
visual work. roundRect is built into the 2D context now:
// One gradient reused; rounded cap via roundRect.
function drawBar(ctx, x, baseY, w, h) {
const g = ctx.createLinearGradient(0, baseY - h, 0, baseY);
g.addColorStop(0, '#f472b6'); // hot tip
g.addColorStop(1, '#38bdf8'); // cool base
ctx.fillStyle = g;
ctx.beginPath();
ctx.roundRect(x, baseY - h, w, h, Math.min(w / 2, 6));
ctx.fill();
}
Peak-hold caps are a second tiny array: each frame, peak[i] = max(peak[i] -
fall, disp[i]), then draw a short bright mark at peak[i]. The
fall rate is the one number to tune — too fast and the caps vanish, too
slow and they hang in the air like dead pixels.
Common pitfalls
- Linear bins (the #1 reason bars look bad). If your visualizer
looks bass-crammed and treble-dead, you are slicing the FFT array evenly. Switch to
log/geometric bin edges. This one change fixes 80% of "my visualizer looks amateur"
complaints. Toggle
scalein the demo to see it both ways. - Too many bins. Crank the bins slider to 160 and the bars go thin, noisy, and hard to read — you are showing more frequency resolution than the eye (or the music) cares about, and each bar averages too few FFT bins to be stable. 32–80 bars is the readable range for most music. More bins is not more impressive.
- Smoothing lag. Push smoothing toward 0.95 and the bars lag the music so badly they feel disconnected; drop it to 0 and they seizure. Tune it for the genre — fast electronic music wants less smoothing than a slow ballad. There is no universal value.
- Peak caps falling too fast (or too slow). The cap’s
fallspeed is its own knob, separate from bar smoothing. Too fast and the caps flicker and disappear; too slow and they float disconnected from the bars. Make it frame-rate aware (scale by delta-time) or it will behave differently at 30 vs 60 fps. - Bin 0 is garbage. The very first FFT bin is the DC / near-DC term and is often a fat useless value that makes your first bar tower over the rest. Start your ranges at bin 1, as the code above does.
Exercises
- Add falling peak-hold caps to the linear stages. Keep a
peak[]array, dopeak[i] = Math.max(peak[i] - fall, disp[i])each frame, and draw a 2px bright line at that height. Tunefalluntil the caps trail transients without floating. (The radial stages already show them — port the idea to the bars.) - Mirror the radial layout into a full ring. In
drawRadial, only sweepcountbars over half the circle (angle = i/count × π) and draw each bar a second time atangle + π(or negate the angle). You get a perfectly symmetric ring like Stage 6 — and it reads as twice as polished for one extra line. - Color by bin index. Replace the static gradient with a hue that
depends on the bar’s position:
hsl(i / count × 320, 90%, 55%). Now bass is one end of the rainbow and treble the other, and the palette itself tells you which part of the spectrum is loud. Try animating the hue offset slowly over time.
What’s next
Episode 03 — Beat Detection: make things hit on the drop. Right now our bars react to loudness, but they do not know when a beat lands. Next we build a proper kick detector — a running-average energy threshold with a refractory window so one kick counts as exactly one beat — and use it to fire flashes, pulses, and scene changes precisely on the downbeat. That is the difference between a visualizer that wiggles and one that performs. The smoothed, binned spectrum you built here is exactly the input that detector reads.