3.5 KiB
<AudioVisualizer>
(no submodules)
Purpose
<AudioVisualizer> is a canvas-based visualiser for a published bus.
It subscribes through the foundation useBus hook (default "master")
and renders one of three modes — waveform, spectrum, or level — into a
<canvas> at the configured tick rate. The component is read-only and
allocates exactly one scratch Float32Array per mount so the
per-frame path is allocation-free in steady state.
The visualiser is intentionally agnostic about the source: anything that publishes to the named bus shows up. When no publisher exists the canvas paints the background only.
Features
- Three modes:
"waveform","spectrum","level". - Configurable width, height, foreground colour, and background.
sampleRateHzcontrols the tick rate (clamped to>= 1).busNameselects which bus to render (default"master").role="img"+ descriptivearia-labelfor screen readers.- Drawing primitives (
drawWaveform/drawSpectrum/drawLevel) are individually exported as@internalfor test coverage.
Usage: Basic Example
import { AudioProvider, AudioVisualizer } from "@suaveplan/react-audio";
export function App() {
return (
<AudioProvider>
<AudioVisualizer />
</AudioProvider>
);
}
Usage: Advanced Example
import { AudioProvider, AudioVisualizer } from "@suaveplan/react-audio";
export function MultiVisualizer() {
return (
<AudioProvider>
<AudioVisualizer mode="waveform" />
<AudioVisualizer mode="spectrum" busName="auxA" />
<AudioVisualizer
mode="level"
color="#0f0"
backgroundColor="#000"
width={128}
height={32}
sampleRateHz={120}
/>
</AudioProvider>
);
}
API Reference
| Prop | Type | Default | Notes |
|---|---|---|---|
className |
string | undef |
— | Forwarded to the <canvas>. |
width |
number | undef |
320 |
Canvas pixel width. |
height |
number | undef |
80 |
Canvas pixel height. |
mode |
VisualizerMode |
"waveform" |
One of the three render modes. |
busName |
string | undef |
"master" |
Which bus to read. |
sampleRateHz |
number | undef |
60 |
Render tick rate. |
color |
string | undef |
"#3aa" |
Foreground colour. |
backgroundColor |
string | undef |
"#111" |
Canvas background colour. |
Implementation Notes
The effect resolves the canvas context once on mount via
canvas.getContext("2d") and gracefully short-circuits when the
context cannot be acquired (test environments without canvas support,
or production browsers under aggressive accessibility settings). When
the bus has no publisher the visualiser still ticks the canvas to
keep the background paint fresh. Spectrum mode uses a naive average
of Math.abs over a downsampled window rather than a real FFT — this
is deliberate so the component has zero non-React runtime dependencies
and remains universally portable.