Beat Detection · How it works & code
Beat Detection (Audio Visualization): Detect beats when energy surge E > C × average energy, and estimate BPM.
Runtime logic
Visiting `/audio/beat`, DemoHost lazy-loads `demos/kits/kit-audio.js` (registry `mod: 'kit-audio'`) and calls `mount(host, { variant: 'beat' })`. mount resolves the variant to family `beat`; `withControls` builds the control panel (6 presets + sliders). `createCanvasStage` creates the `<canvas>` (HiDPI ≤ 2×, ResizeObserver) and the info panel. The family’s `build(S)` initialises state and returns the per-frame callback. Every `requestAnimationFrame`: read controls, advance a speed-scaled clock (dt ≤ 50 ms), run the frame callback; returned readouts go to the info panel. Pointer down/drag/move updates the interaction (drag handles, hover readouts); when untouched and auto-demo is on, the pointer follows a Lissajous path. With the top-right Sound switch on, sound plays through the shared AudioContext; off = muted. Changing parameters: colour/speed/size apply live; structural ones remount; leaving the page cancels rAF, removes listeners and frees resources.
Environment
Canvas 2D: 2D canvas drawing; requestAnimationFrame: Display-synced animation loop; ResizeObserver: Canvas follows container size; Pointer Events: Unified mouse/touch/pen events; devicePixelRatio: Crisp HiDPI rendering (capped at 2×) · react 18.3.1, react-router-dom 6.30.6, vite 5.4.21
Dependencies
react 18.3.1
Imported APIs
withControls — Wraps the demo in the shared control panel (presets, sliders, reset); hot-updates or remounts on change; paramsFromSpec — Turns the spec (colour/speed/size/count/extras) into control-panel parameter definitions; createCanvasStage — Shared Canvas 2D stage: canvas + info panel, HiDPI, one rAF loop, pointer state, idle auto-pointer; hueOf — Hue of a colour (0–360°); clamp — Clamps a value to a range; TAU — Constant 2π; fmt — Number formatting (fixed decimals); F — Formula block HTML; S.clear — Clears with the background colour (translucent = trails); S.onDown — Pointer down; S.onFrame — Registers a per-frame callback; its return value feeds the info panel; ctx.beginPath() — Starts a new path; ctx.arc() — Adds a circular arc (center, radius, start/end angle); ctx.stroke() — Strokes the current path; ctx.createRadialGradient() — Creates a radial gradient; ctx.fill() — Fills the current path; ctx.strokeRect() — Strokes a rectangle; ctx.lineTo() — Adds a straight line to a point; ctx.moveTo() — Moves the pen without drawing; ctx.setLineDash() — Sets the dash pattern for strokes; ctx.arcTo() — Adds an arc using tangent lines; ctx.closePath() — Closes the current sub-path; ctx.fillText() — Draws filled text; ctx.measureText() — Measures text width
Source code
frontend/src/demos/kits/kit-audio.js: FAM.beat (L641-L694)
Code walkthrough
L643-643: Control definitions (colour/speed/size/count/extras): Pulse color, Pulse size, Snare BPM, Detection sensitivity C, Average window s, Only look at low frequency (drum). L644-644: Preset buttons: name → parameter overrides (6). L645-653: Info-panel content: live rows(v), formula, notes, params, steps. L654-693: Init function: sets up state and returns the per-frame callback: draws with Canvas 2D `beginPath`, `arc`, `stroke`, `createRadialGradient`, `fill`, `strokeRect` …; produces/reads sound via `A.voices`; math via `Math.round`, `Math.exp`, `Math.min`, `Math.max`; returns readouts `bpm`, `est`, `ring`, `low`, `e`, `avg`, `sens` … to the info panel.
Principles
Energy E(t) = sum of low frequency band power (approximately 40-150 Hz) Threshold = C × Ē (Ē = Average energy over time) E > Threshold 且 It's a local peak → It's one shot BPM = 60 / Average interval Music software goes with the rhythm Beat Detection 。最朴素的办法:持续计算低频(底鼓所在频段)的 Energy , Again"The average energy of the recent period"Compare——If it's suddenly higher than average, C Double, just think it's a shot. The lower curve is the energy that changes over time, the dotted line is the threshold C×Ē,红点是被判为节拍的时刻。把相邻两拍的时间间隔取平均,就能估算 BPM (Every minute. C 太小会把小鼓、哈特也当成拍;太大又会漏拍。