A standalone canvas spectrum driven by real Web Audio data.
Default
With Player
Ready to load audio.
Microphone
Purpose
An audio visualizer turns sound into a moving display so people can see how the audio changes as it plays.
Parts & Composition
Render AudioVisualizer alongside the audio source. Connect a media element, stream, or existing analyser, and use children for overlay content such as a label or playback control.
API & Props
One source: audioRef, mediaStream, or analyserNode. connect() from user gesture when using element ref.
| Prop | Purpose |
|---|---|
size | xs (h-36), sm (h-52), md (h-72, default), or lg (h-96). |
variant | radial, halo, bars, wave, silk, orb, led, scope |
theme | classic, acoustic, neon, sunset, progress |
barCount, sensitivity, smoothing, fftSize | Analysis tuning |
enabled, frameRate, onTelemetry | Sampling control |
Ref: getCanvas(), getAnalyser(). Export useAudioAnalyzer for custom canvas.
State & forms
Remote audio needs crossOrigin="anonymous" before load. Consumer owns routing when passing analyserNode.
Theming, Layout & Responsiveness
Transparent canvas; optional CSS background on container. Chart/primary tokens in classic theme.
Default height ~18rem; set via className.
Motion & Accessibility
Pauses when hidden, paused, or reduced motion (snapshot mode).
Decorative canvas; status belongs in surrounding UI.
Guidance for Coding Agents
Install this component using the command in the Install tab. Read this Info page before implementing.
Connect the visualizer to the media source using the public audio integration. Size its container explicitly and let the player own playback. Use decorative semantics when the animation adds no information beyond the audio.
Keep AudioVisualizer decorative (aria-hidden) and surface playback/recording status in surrounding UI text or live regions.
Start from the closest Preview → Usage example and use this page’s API table for component parts and options.
Registry
Client only; no extra animation package.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/audio-visualizer'use client';
import { cva } from 'class-variance-authority';
import {
type ComponentProps,
type Ref,
useEffect,
useEffectEvent,
useImperativeHandle,
useRef,
} from 'react';
import type { StandardControlSize } from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
import {
ACOUSTIC_ZONES,
type AudioAnalyzerOptions,
type AudioVisualizerTheme,
type AudioVisualizerVariant,
clamp,
getAcousticZoneForHz,
getAudioBandEnergy,
getVisualBandEnergy,
useAudioAnalyzer,
VISUALIZER_THEMES,
} from './analyzer';
const audioVisualizerSizes = cva(
'relative isolate w-full min-w-0 overflow-hidden rounded-lg text-primary',
{
variants: {
size: {
xs: 'h-36',
sm: 'h-52',
md: 'h-72',
lg: 'h-96',
} satisfies Record<StandardControlSize, string>,
},
defaultVariants: { size: 'md' },
},
);
type AudioVisualizerTelemetry = {
bands: Readonly<Record<(typeof ACOUSTIC_ZONES)[number]['id'], number>>;
};
type AudioVisualizerHandle = {
connect: () => Promise<AnalyserNode | null>;
getAnalyser: () => AnalyserNode | null;
getCanvas: () => HTMLCanvasElement | null;
};
type AudioVisualizerProps = Omit<ComponentProps<'div'>, 'onError' | 'ref'> &
AudioAnalyzerOptions & {
ref?: Ref<AudioVisualizerHandle>;
size?: StandardControlSize;
variant?: AudioVisualizerVariant;
theme?: AudioVisualizerTheme;
barCount?: number;
sensitivity?: number;
barThickness?: number;
baseRadiusRatio?: number;
mirror?: boolean;
bassPulse?: boolean;
showGuides?: boolean;
showPeakCaps?: boolean;
/** For external sources; media-element progress is read directly otherwise. */
progress?: number;
enabled?: boolean;
frameRate?: number;
/** At most ten callbacks per second. Values are normalized FFT magnitude, not dB/SPL. */
onTelemetry?: (telemetry: AudioVisualizerTelemetry) => void;
};
function AudioVisualizer({
ref,
size = 'md',
audioRef,
mediaStream,
analyserNode,
fftSize,
smoothing = 0.68,
variant = 'radial',
theme = 'classic',
barCount = 104,
sensitivity = 1.35,
barThickness = 4.2,
baseRadiusRatio = 0.27,
mirror = false,
bassPulse = true,
showGuides = false,
showPeakCaps = true,
progress = 0,
enabled = true,
frameRate = 60,
onTelemetry,
onError,
className,
children,
...props
}: AudioVisualizerProps) {
const container = useRef<HTMLDivElement>(null);
const canvas = useRef<HTMLCanvasElement>(null);
const analysis = useAudioAnalyzer({
audioRef,
mediaStream,
analyserNode,
fftSize,
smoothing,
onError,
});
const { analyserRef, connect, ready, error, node } = analysis;
useImperativeHandle(
ref,
() => ({ connect, getAnalyser: () => analyserRef.current, getCanvas: () => canvas.current }),
[connect, analyserRef],
);
const options = useEffectEvent(() => ({
variant,
theme,
barCount,
sensitivity,
barThickness,
baseRadiusRatio,
mirror,
bassPulse,
showGuides,
showPeakCaps,
progress,
frameRate,
smoothing,
onTelemetry,
}));
const redraw = useRef<(() => void) | null>(null);
const retained = useRef({
amplitudes: new Float32Array(256),
peaks: new Float32Array(256),
frequencies: new Uint8Array(0),
samples: new Uint8Array(0),
peakVelocities: new Float32Array(256),
phase: 0,
previousBass: 0,
shockwaves: [] as { radiusOffset: number; alpha: number }[],
});
useEffect(() => {
const surface = container.current;
const element = canvas.current;
const context = element?.getContext('2d');
if (!surface || !element || !context) return;
let width = 1,
height = 1,
dpr = 1,
frame = 0,
last = 0,
telemetryAt = 0;
let visible = true;
let ink = '',
muted = '',
paletteInk: string[] = [];
const refreshColors = () => {
const style = getComputedStyle(surface);
ink = style.color;
muted = style.getPropertyValue('--muted-foreground').trim() || ink;
paletteInk = ['--primary', '--chart-2', '--chart-3', '--chart-4'].map(
(token) => style.getPropertyValue(token).trim() || ink,
);
};
const tint = (color: string, opacity: number) =>
`color-mix(in srgb,${color} ${Math.round(opacity * 100)}%,transparent)`;
let { frequencies, samples } = retained.current;
const { amplitudes, peaks } = retained.current;
const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
const media = audioRef?.current;
const active = () =>
enabled &&
visible &&
!document.hidden &&
(!media || (!media.paused && !media.ended)) &&
analyserRef.current?.context.state === 'running';
const draw = (now: number, sample: boolean) => {
const config = options();
const analyser = analyserRef.current;
const count = Math.round(clamp(config.barCount, 8, 256, 104));
const sensitivity = clamp(config.sensitivity, 0, 5, 1.35);
const thickness = clamp(config.barThickness, 0.5, 12, 3);
const min = Math.min(width, height);
const cx = width / 2,
cy = height / 2;
const rate = analyser?.context.sampleRate ?? 48000;
const high = Math.min(20000, rate / 2);
const position =
media && Number.isFinite(media.duration) && media.duration > 0
? media.currentTime / media.duration
: clamp(config.progress, 0, 1, 0);
if (sample && analyser) {
if (frequencies.length !== analyser.frequencyBinCount)
frequencies = new Uint8Array(analyser.frequencyBinCount);
if (config.variant === 'scope' && samples.length !== analyser.fftSize)
samples = new Uint8Array(analyser.fftSize);
retained.current.frequencies = frequencies;
retained.current.samples = samples;
analyser.getByteFrequencyData(frequencies);
if (config.variant === 'scope') analyser.getByteTimeDomainData(samples);
if (config.onTelemetry && now - telemetryAt >= 100) {
const bands = Object.fromEntries(
ACOUSTIC_ZONES.map((zone) => [
zone.id,
getAudioBandEnergy(frequencies, rate, zone.minHz, zone.maxHz),
]),
) as AudioVisualizerTelemetry['bands'];
config.onTelemetry({ bands });
telemetryAt = now;
}
}
context.setTransform(dpr, 0, 0, dpr, 0, 0);
const ctx = context;
const {
variant,
theme,
mirror,
bassPulse: requestedPulse,
showGuides,
showPeakCaps,
} = config;
const bassPulse = requestedPulse && !motion.matches;
const barCount = count;
const barThickness = thickness;
const baseRadiusRatio = clamp(config.baseRadiusRatio, 0.1, 0.34, 0.27);
const frequencyData = frequencies;
const timeDomainData = samples;
const sampleRate = rate;
const progress = position;
const minDim = min;
const centerX = cx,
centerY = cy;
const palette = VISUALIZER_THEMES[theme];
const paint = (i: number, total: number, position: number, amplitude: number, hz: number) => {
if (theme === 'classic')
return tint(ink, Math.min(1, 0.24 + 0.76 * (1 - i / total) ** 1.35 + amplitude * 0.28));
if (theme === 'progress')
return tint(i / total <= position ? ink : muted, i / total <= position ? 0.9 : 0.35);
return palette.getBarStyle(i, total, position, amplitude, hz);
};
ctx.clearRect(0, 0, width, height);
const delta = last ? Math.min(100, now - last) / 16.667 : 1;
if (sample && !motion.matches) retained.current.phase += 0.025 * delta;
const idlePhase = retained.current.phase;
const band = (low: number, high: number) =>
getVisualBandEnergy(frequencyData, low, high, sampleRate);
const subBassEnergy = band(20, 60),
bassEnergy = band(60, 250);
const lowMidsEnergy = band(250, 500),
midrangeEnergy = band(500, 2000);
const upperMidsEnergy = band(2000, 4000),
presenceEnergy = band(4000, 6000),
brillianceEnergy = band(6000, 20000);
const hasActiveAudio =
subBassEnergy +
bassEnergy +
lowMidsEnergy +
midrangeEnergy +
upperMidsEnergy +
presenceEnergy +
brillianceEnergy >
0.012;
const combinedLow = subBassEnergy * 0.55 + bassEnergy * 0.45;
const lowDelta = combinedLow - retained.current.previousBass;
if (sample) {
if (
bassPulse &&
lowDelta > 0.14 &&
combinedLow > 0.38 &&
retained.current.shockwaves.length < 3
)
retained.current.shockwaves.push({
radiusOffset: 0,
alpha: Math.min(0.5, lowDelta * 1.5),
});
retained.current.previousBass = combinedLow * 0.75 + retained.current.previousBass * 0.25;
}
const currentAmps = amplitudes,
peakAmps = peaks,
peakVelocities = retained.current.peakVelocities;
const smoothing = clamp(config.smoothing, 0, 0.99, 0.68);
const smooth = (prev: number, target: number, attack: number) =>
sample
? prev + (target - prev) * (1 - (1 - (target > prev ? attack : 1 - smoothing)) ** delta)
: prev;
const logMin = Math.log10(20),
logMax = Math.log10(high);
const getZoneSpan = (normStart: number, normEnd: number) => {
if (mirror) {
const mapped = Math.abs((normStart + normEnd) / 2 - 0.5) * 2;
const half = (normEnd - normStart) / 2;
normStart = Math.max(0, mapped - half);
normEnd = Math.min(1, mapped + half);
}
const lowHz = 10 ** (logMin + normStart * (logMax - logMin));
const highHz = Math.min(
high,
Math.max(lowHz + 4, 10 ** (logMin + normEnd * (logMax - logMin))),
);
return { lowHz, highHz, centerHz: (lowHz + highHz) / 2 };
};
if (showGuides && ['radial', 'halo', 'orb'].includes(variant)) {
ctx.beginPath();
ctx.arc(centerX, centerY, minDim * baseRadiusRatio, 0, Math.PI * 2);
ctx.strokeStyle = tint(ink, 0.1);
ctx.lineWidth = 1;
ctx.stroke();
}
// --- VARIANT: BARS ---
if (variant === 'bars') {
const numCols = Math.min(84, Math.max(24, Math.round(barCount * 0.55)));
const chartMarginX = Math.max(12, width * 0.03);
const chartBottomY = height - Math.max(16, height * 0.08);
const maxColHeight = Math.max(30, chartBottomY - Math.max(24, height * 0.14));
const totalChartWidth = Math.max(40, width - chartMarginX * 2);
const colWidth = totalChartWidth / numCols;
for (let i = 0; i < numCols; i++) {
const ratio = i / numCols;
const { lowHz, highHz, centerHz } = getZoneSpan(ratio, (i + 1) / numCols);
let targetAmp = 0;
if (hasActiveAudio) {
targetAmp = Math.min(
1.05,
getVisualBandEnergy(frequencyData, lowHz, highHz, sampleRate) *
sensitivity *
(1.15 - ratio * 0.32),
);
} else {
targetAmp = 0;
}
const prev = currentAmps[i] || 0;
const smoothed = smooth(prev, targetAmp, 0.82);
currentAmps[i] = smoothed;
if (sample && smoothed >= (peakAmps[i] || 0)) {
peakAmps[i] = smoothed;
peakVelocities[i] = 0;
} else if (sample) {
peakVelocities[i] = (peakVelocities[i] || 0) + 0.0018;
peakAmps[i] = Math.max(smoothed, (peakAmps[i] || 0) - peakVelocities[i]);
}
const colH = Math.max(4, smoothed * maxColHeight);
const x = chartMarginX + i * colWidth;
const y = chartBottomY - colH;
ctx.fillStyle =
theme === 'classic'
? ratio < 0.45
? paletteInk[0]
: tint(paletteInk[0], 0.7)
: paint(i, numCols, progress, smoothed, centerHz);
ctx.fillRect(x, y, Math.max(1.5, colWidth - 1.2), colH);
if (showPeakCaps)
ctx.fillRect(
x,
chartBottomY - peakAmps[i] * maxColHeight - 3,
Math.max(1.5, colWidth - 1.2),
1,
);
}
return;
}
// --- VARIANT: WAVE ---
if (variant === 'wave') {
const pillCount = Math.min(56, Math.max(9, Math.round(barCount * 0.28)));
const waveWidth = Math.min(width * 0.78, pillCount * 16);
const startX = centerX - waveWidth * 0.5;
const stepX = pillCount > 1 ? waveWidth / (pillCount - 1) : 0;
const maxH = Math.min(height * 0.56, 220);
for (let i = 0; i < pillCount; i++) {
const ratio = i / pillCount;
const { lowHz, highHz, centerHz } = getZoneSpan(ratio, (i + 1) / pillCount);
let targetAmp = 0;
if (hasActiveAudio) {
targetAmp = Math.min(
1.0,
getVisualBandEnergy(frequencyData, lowHz, highHz, sampleRate) *
sensitivity *
(0.65 + 0.35 * Math.sin(ratio * Math.PI)),
);
} else {
targetAmp = 0;
}
const prev = currentAmps[i] || 0;
const smoothed = smooth(prev, targetAmp, 0.84);
currentAmps[i] = smoothed;
const totalH = Math.max(6, barThickness * 1.4) + smoothed * maxH;
const x = startX + i * stepX;
ctx.beginPath();
ctx.moveTo(x, centerY - totalH * 0.5);
ctx.lineTo(x, centerY + totalH * 0.5);
ctx.strokeStyle =
theme === 'classic'
? tint(ink, 0.9)
: paint(i, pillCount, progress, smoothed, centerHz);
ctx.lineWidth = Math.max(3, barThickness * 1.05);
ctx.lineCap = 'round';
ctx.stroke();
}
return;
}
// --- VARIANT: SILK ---
if (variant === 'silk') {
const layers = [
{
energy: Math.max(0.08, subBassEnergy * 0.55 + bassEnergy * 0.55),
freq: 1.6,
speed: 1.05,
alpha: 0.45,
},
{
energy: Math.max(0.08, lowMidsEnergy * 0.5 + midrangeEnergy * 0.7),
freq: 2.7,
speed: -1.35,
alpha: 0.45,
},
{
energy: Math.max(0.08, upperMidsEnergy * 0.65 + presenceEnergy * 0.65),
freq: 3.9,
speed: 1.75,
alpha: 0.48,
},
{
energy: Math.max(0.06, brillianceEnergy * 1.15),
freq: 5.2,
speed: -2.1,
alpha: 0.65,
},
];
const maxAmp = Math.min(height * 0.34, 180);
layers.forEach((layer, idx) => {
const amp = (hasActiveAudio ? layer.energy * sensitivity : 0) * maxAmp;
ctx.beginPath();
const steps = 80; // Optimized step count for performance
for (let s = 0; s <= steps; s++) {
const normX = s / steps;
const x = normX * width;
const env = Math.sin(normX * Math.PI) ** 1.6;
const phase = idlePhase * layer.speed + idx * 1.3;
const yOffset = Math.sin(normX * Math.PI * 2 * layer.freq + phase) * amp * env;
const y = centerY + yOffset;
if (s === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.strokeStyle =
theme === 'classic'
? tint(paletteInk[idx], Math.min(1, layer.alpha + layer.energy * 0.35))
: paint(idx, layers.length, progress, layer.energy, [100, 1000, 4500, 10000][idx]);
ctx.lineWidth = 2;
ctx.stroke();
});
return;
}
// --- VARIANT: ORB ---
if (variant === 'orb') {
const baseOrbR = minDim * (baseRadiusRatio * 0.95);
const maxMorph = minDim * 0.14;
const numVerts = 64;
ctx.beginPath();
for (let i = 0; i <= numVerts; i++) {
const norm = (i % numVerts) / numVerts;
const angle = norm * Math.PI * 2 - Math.PI * 0.5;
const bandRatio = Math.abs(norm - 0.5) * 2;
const { lowHz, highHz } = getZoneSpan(bandRatio, Math.min(1, bandRatio + 0.04));
const amp = hasActiveAudio
? getVisualBandEnergy(frequencyData, lowHz, highHz, sampleRate) * sensitivity
: 0;
const r = baseOrbR + amp * maxMorph + Math.sin(angle * 4 + idlePhase) * (minDim * 0.012);
const x = centerX + Math.cos(angle) * r;
const y = centerY + Math.sin(angle) * r;
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.closePath();
ctx.strokeStyle =
theme === 'classic' ? tint(ink, 0.85) : paint(20, 100, progress, 0.8, 600);
ctx.lineWidth = 2.5;
ctx.stroke();
return;
}
// --- VARIANT: HALO ---
if (variant === 'halo') {
const baseHaloR = minDim * (baseRadiusRatio * 0.96);
const maxHaloRay = minDim * 0.23;
const rayCount = Math.max(72, Math.round(barCount * 0.9));
const lowDrive = subBassEnergy * 0.55 + bassEnergy * 0.5;
const midDrive = lowMidsEnergy * 0.3 + midrangeEnergy * 0.65;
const highDrive = presenceEnergy * 0.65 + brillianceEnergy * 0.85;
const haloLayers = [
{ energy: lowDrive, freq: 2, speed: 0.65, shift: 0 },
{
energy: midDrive,
freq: 2,
speed: -0.82,
shift: 1.0,
},
{
energy: highDrive,
freq: 3,
speed: 0.95,
shift: 2.0,
},
];
haloLayers.forEach((l, layerIndex) => {
for (let i = 0; i < rayCount; i++) {
const norm = i / rayCount;
const angle = -Math.PI * 0.5 + norm * Math.PI * 2 + l.shift * 0.3;
const lobe =
Math.max(0, (Math.sin(angle * l.freq + idlePhase * l.speed) + 1) * 0.5) ** 1.5;
const rayLen = Math.max(
2.5,
lobe * maxHaloRay * Math.min(1.35, (0.2 + l.energy * 1.1) * sensitivity),
);
const cosA = Math.cos(angle);
const sinA = Math.sin(angle);
const x1 = centerX + cosA * baseHaloR;
const y1 = centerY + sinA * baseHaloR;
const x2 = centerX + cosA * (baseHaloR + rayLen);
const y2 = centerY + sinA * (baseHaloR + rayLen);
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle =
theme === 'classic'
? tint(paletteInk[layerIndex], 0.7)
: paint(
i,
rayCount,
progress,
l.energy,
getZoneSpan(norm, (i + 1) / rayCount).centerHz,
);
ctx.lineWidth = Math.max(1.4, barThickness * 0.48);
ctx.lineCap = 'round';
ctx.stroke();
}
});
return;
}
// --- VARIANT: LED ---
if (variant === 'led') {
const numCols = Math.min(42, Math.max(16, Math.round(barCount * 0.3)));
const numRows = 18;
const marginX = Math.max(16, width * 0.05);
const bottomY = height - Math.max(20, height * 0.1);
const topY = Math.max(32, height * 0.16);
const gridW = Math.max(60, width - marginX * 2);
const colStep = gridW / numCols;
const rowStep = (bottomY - topY) / numRows;
for (let c = 0; c < numCols; c++) {
const ratio = c / numCols;
const { lowHz, highHz } = getZoneSpan(ratio, (c + 1) / numCols);
const target = hasActiveAudio
? Math.min(
1.0,
getVisualBandEnergy(frequencyData, lowHz, highHz, sampleRate) * sensitivity,
)
: 0;
const prev = currentAmps[c] || 0;
const smoothed = smooth(prev, target, 0.85);
currentAmps[c] = smoothed;
const lit = Math.round(smoothed * numRows);
const x = marginX + c * colStep;
for (let r = 0; r < numRows; r++) {
const y = bottomY - (r + 1) * rowStep;
if (r < lit) {
ctx.fillStyle =
theme !== 'classic'
? paint(
c,
numCols,
progress,
smoothed,
getZoneSpan(ratio, (c + 1) / numCols).centerHz,
)
: r / numRows > 0.8
? paletteInk[2]
: r / numRows > 0.6
? paletteInk[1]
: paletteInk[0];
ctx.fillRect(x, y, Math.max(3, colStep - 3.5), Math.max(2.5, rowStep - 2.5));
}
}
}
return;
}
// --- VARIANT: SCOPE ---
if (variant === 'scope') {
const marginX = Math.max(16, width * 0.04);
const scopeW = width - marginX * 2;
const maxAmp = Math.min(height * 0.36, 200);
ctx.beginPath();
const slices = 120;
for (let i = 0; i <= slices; i++) {
const norm = i / slices;
const x = marginX + norm * scopeW;
let sample = 0;
if (hasActiveAudio) {
const bufIdx = Math.min(
timeDomainData.length - 1,
Math.floor(norm * timeDomainData.length),
);
sample = ((timeDomainData[bufIdx] - 128) / 128) * sensitivity;
} else {
sample = 0;
}
const y = centerY + sample * maxAmp;
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.strokeStyle =
theme === 'classic' ? tint(ink, 0.9) : paint(50, 100, progress, 0.85, 1200);
ctx.lineWidth = 2;
ctx.stroke();
return;
}
// --- VARIANT: RADIAL (Default) ---
const lowImpact = subBassEnergy * 0.6 + bassEnergy * 0.4;
const pulse = bassPulse && hasActiveAudio ? lowImpact ** 1.3 * (minDim * 0.045) : 0;
const baseR = minDim * baseRadiusRatio + pulse;
const maxBarH = minDim * 0.175;
const minBarH = Math.max(3.5, minDim * 0.011);
if (bassPulse && retained.current.shockwaves.length > 0) {
for (let s = retained.current.shockwaves.length - 1; s >= 0; s--) {
const sw = retained.current.shockwaves[s];
if (sample) sw.radiusOffset += minDim * 0.0075 * delta;
if (sample) sw.alpha *= 0.92 ** delta;
ctx.beginPath();
ctx.arc(centerX, centerY, baseR + sw.radiusOffset, 0, Math.PI * 2);
ctx.strokeStyle = tint(ink, sw.alpha);
ctx.lineWidth = 1.5;
ctx.stroke();
if (sw.alpha < 0.03) retained.current.shockwaves.splice(s, 1);
}
}
const startAngle = -Math.PI * 0.5;
for (let i = 0; i < barCount; i++) {
const norm = i / barCount;
const angle = startAngle - norm * Math.PI * 2;
const { lowHz, highHz, centerHz } = getZoneSpan(norm, (i + 1) / barCount);
const target = hasActiveAudio
? Math.min(
1.35,
getVisualBandEnergy(frequencyData, lowHz, highHz, sampleRate) * sensitivity,
)
: 0;
const prev = currentAmps[i] || 0;
const smoothed = smooth(prev, target, 0.82);
currentAmps[i] = smoothed;
const barH = minBarH + smoothed * maxBarH;
const cosA = Math.cos(angle);
const sinA = Math.sin(angle);
const x1 = centerX + cosA * baseR;
const y1 = centerY + sinA * baseR;
const x2 = centerX + cosA * (baseR + barH);
const y2 = centerY + sinA * (baseR + barH);
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = paint(i, barCount, progress, smoothed, centerHz);
ctx.lineWidth = barThickness;
ctx.lineCap = 'round';
ctx.stroke();
}
};
const tick = (now: number) => {
frame = 0;
if (!active()) return;
const interval = 1000 / clamp(options().frameRate, 1, 60, 30);
if (now - last >= interval) {
draw(now, true);
last = now;
}
if (!motion.matches) frame = requestAnimationFrame(tick);
};
const wake = () => {
if (frame) cancelAnimationFrame(frame);
frame = 0;
if (active()) frame = requestAnimationFrame(tick);
};
const resetSignal = () => {
amplitudes.fill(0);
peaks.fill(0);
frequencies.fill(0);
samples.fill(128);
retained.current.phase = 0;
retained.current.previousBass = 0;
retained.current.shockwaves.length = 0;
retained.current.peakVelocities.fill(0);
draw(performance.now(), false);
wake();
};
const resize = () => {
refreshColors();
const box = surface.getBoundingClientRect();
width = Math.max(1, box.width);
height = Math.max(1, box.height);
dpr = Math.min(window.devicePixelRatio || 1, 2);
const pixelWidth = Math.round(width * dpr),
pixelHeight = Math.round(height * dpr);
if (element.width !== pixelWidth) element.width = pixelWidth;
if (element.height !== pixelHeight) element.height = pixelHeight;
draw(performance.now(), false);
wake();
};
const themeObserver = new MutationObserver(() => {
refreshColors();
draw(performance.now(), false);
});
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class', 'style'],
});
themeObserver.observe(surface, { attributes: true, attributeFilter: ['class', 'style'] });
const observer = new ResizeObserver(resize);
observer.observe(surface);
const intersection = new IntersectionObserver(([entry]) => {
visible = entry.isIntersecting;
wake();
});
intersection.observe(surface);
const subscriptions = new AbortController();
const listenerOptions = { signal: subscriptions.signal };
for (const event of ['play', 'playing', 'pause', 'ended', 'seeked'])
media?.addEventListener(event, wake, listenerOptions);
node?.context.addEventListener('statechange', wake, listenerOptions);
media?.addEventListener('emptied', resetSignal, listenerOptions);
document.addEventListener('visibilitychange', wake, listenerOptions);
motion.addEventListener('change', wake, listenerOptions);
redraw.current = () => {
if (!active() || motion.matches) {
refreshColors();
draw(performance.now(), false);
}
};
resize();
return () => {
redraw.current = null;
cancelAnimationFrame(frame);
observer.disconnect();
themeObserver.disconnect();
intersection.disconnect();
subscriptions.abort();
};
}, [audioRef, analyserRef, node, enabled]);
// Refresh a paused canvas when visual options change without rebuilding subscriptions.
// biome-ignore lint/correctness/useExhaustiveDependencies: options invalidate the retained canvas drawing.
useEffect(() => {
redraw.current?.();
}, [
variant,
theme,
barCount,
sensitivity,
smoothing,
barThickness,
baseRadiusRatio,
mirror,
bassPulse,
showGuides,
showPeakCaps,
progress,
frameRate,
]);
return (
<div
{...props}
ref={container}
data-slot="audio-visualizer"
data-size={size}
data-variant={variant}
data-theme={theme}
data-ready={ready || undefined}
data-error={error ? '' : undefined}
className={cn(audioVisualizerSizes({ size }), className)}
>
<canvas
ref={canvas}
tabIndex={-1}
aria-hidden="true"
className="pointer-events-none block size-full"
/>
{children}
</div>
);
}
export type {
AudioAnalyzerOptions,
AudioVisualizerHandle,
AudioVisualizerProps,
AudioVisualizerTelemetry,
AudioVisualizerTheme,
AudioVisualizerVariant,
};
export {
ACOUSTIC_ZONES,
AudioVisualizer,
getAcousticZoneForHz,
getAudioBandEnergy,
useAudioAnalyzer,
VISUALIZER_THEMES,
};
'use client';
import { type RefObject, useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';
/** Conventional frequency regions for visual grouping, not a loudness/BPM measurement. */
const ACOUSTIC_ZONES = [
{ id: 'subBass', name: 'Sub-bass', minHz: 20, maxHz: 60, hue: 350 },
{ id: 'bass', name: 'Bass', minHz: 60, maxHz: 250, hue: 24 },
{ id: 'lowMids', name: 'Low mids', minHz: 250, maxHz: 500, hue: 48 },
{ id: 'midrange', name: 'Midrange', minHz: 500, maxHz: 2000, hue: 155 },
{ id: 'upperMids', name: 'Upper mids', minHz: 2000, maxHz: 4000, hue: 190 },
{ id: 'presence', name: 'Presence', minHz: 4000, maxHz: 6000, hue: 240 },
{ id: 'brilliance', name: 'Brilliance', minHz: 6000, maxHz: 20000, hue: 292 },
] as const;
function getAcousticZoneForHz(hz: number) {
return ACOUSTIC_ZONES.find((zone) => hz <= zone.maxHz) ?? ACOUSTIC_ZONES[6];
}
function clamp(value: number, min: number, max: number, fallback: number) {
return Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;
}
/** Average normalized FFT magnitude for a band; bins above Nyquist contribute nothing. */
function getAudioBandEnergy(data: Uint8Array, sampleRate: number, low: number, high: number) {
if (
!data.length ||
!Number.isFinite(sampleRate) ||
sampleRate <= 0 ||
!Number.isFinite(low) ||
!Number.isFinite(high) ||
high <= low
)
return 0;
const nyquist = sampleRate / 2;
const from = Math.max(0, (low / nyquist) * data.length);
const to = Math.min(data.length, (high / nyquist) * data.length);
if (from >= to) return 0;
let sum = 0;
for (let i = Math.floor(from); i < Math.ceil(to); i++) {
sum += data[i] * (Math.min(i + 1, to) - Math.max(i, from));
}
return sum / ((to - from) * 255);
}
// A media element can only have one MediaElementSource. Keep its audible route intact
// when visualizers unmount; each subscriber owns only its separate analysis branch.
type MediaGraphRegistry = {
elements: WeakMap<HTMLMediaElement, MediaElementAudioSourceNode>;
context?: AudioContext;
};
// Fast Refresh can replace this module while retaining the actual audio element.
// Keep its irreversible source association across reloads and duplicate module copies.
const graphKey = Symbol.for('component-lib.audio-visualizer.media-graph.v1');
const graphScope = globalThis as typeof globalThis & {
[key: symbol]: MediaGraphRegistry | undefined;
};
const mediaGraph = graphScope[graphKey] ?? { elements: new WeakMap() };
graphScope[graphKey] = mediaGraph;
type AudioAnalyzerOptions = {
audioRef?: RefObject<HTMLMediaElement | null>;
mediaStream?: MediaStream | null;
analyserNode?: AnalyserNode | null;
fftSize?: number;
smoothing?: number;
onError?: (message: string) => void;
};
function useAudioAnalyzer({
audioRef,
mediaStream,
analyserNode,
fftSize = 8192,
smoothing = 0.68,
onError,
}: AudioAnalyzerOptions = {}) {
const analyserRef = useRef<AnalyserNode | null>(null);
const owned = useRef<{
context: AudioContext;
analyser: AnalyserNode;
source: AudioNode;
stream: boolean;
} | null>(null);
const [error, setError] = useState<string | null>(null);
const [node, setNode] = useState<AnalyserNode | null>(null);
const generation = useRef(0);
const size = 2 ** Math.round(Math.log2(clamp(fftSize, 32, 32768, 8192)));
const smoothingValue = clamp(smoothing, 0, 0.99, 0.68);
const connect = useCallback(async () => {
const version = generation.current;
try {
if (
Number(Boolean(audioRef)) + Number(Boolean(mediaStream)) + Number(Boolean(analyserNode)) >
1
)
throw new Error('Provide one audio source: audioRef, mediaStream, or analyserNode.');
if (analyserNode) {
analyserRef.current = analyserNode;
setNode(analyserNode);
setError(null);
// Caller owns external nodes, their settings, routing, and context activation.
return analyserNode;
}
const element = audioRef?.current;
if (!element && !mediaStream) return null;
if (!owned.current) {
if (!window.AudioContext) throw new Error('Web Audio is unavailable in this browser.');
if (element) {
const url = new URL(element.currentSrc || element.src, document.baseURI);
if (url.protocol !== 'blob:' && url.origin !== location.origin && !element.crossOrigin)
throw new Error(
'Remote audio requires crossOrigin="anonymous" before loading and a CORS-enabled source.',
);
}
if (element && !mediaGraph.context) mediaGraph.context = new AudioContext();
const context = element ? (mediaGraph.context as AudioContext) : new AudioContext();
const analyser = context.createAnalyser();
analyser.fftSize = size;
analyser.minDecibels = -92;
analyser.maxDecibels = -12;
analyser.smoothingTimeConstant = smoothingValue;
let source: AudioNode;
try {
if (element) {
let cached = mediaGraph.elements.get(element);
if (!cached) {
cached = context.createMediaElementSource(element);
cached.connect(context.destination);
mediaGraph.elements.set(element, cached);
}
source = cached;
} else source = context.createMediaStreamSource(mediaStream as MediaStream);
source.connect(analyser);
} catch (cause) {
analyser.disconnect();
if (!element) void context.close().catch(() => {});
throw cause;
}
owned.current = { context, analyser, source, stream: !element };
analyserRef.current = analyser;
}
const connection = owned.current;
if (connection.context.state === 'suspended') await connection.context.resume();
// Ignore completion from a source that was replaced or unmounted while resuming.
if (owned.current !== connection) return null;
setNode(connection.analyser);
setError(null);
return connection.analyser;
} catch (cause) {
if (version !== generation.current) return null;
const message = cause instanceof Error ? cause.message : 'Unable to connect audio analysis.';
setError(message);
onError?.(message);
return null;
}
}, [audioRef, mediaStream, analyserNode, size, smoothingValue, onError]);
const activateLatest = useEffectEvent(() => {
void connect();
});
useEffect(() => {
setNode(null);
setError(null);
const element = audioRef?.current;
const activate = () => {
activateLatest();
};
element?.addEventListener('play', activate);
if (analyserNode || mediaStream || (element && !element.paused)) activate();
return () => {
generation.current++;
element?.removeEventListener('play', activate);
const connection = owned.current;
if (connection) {
connection.source.disconnect(connection.analyser);
connection.analyser.disconnect();
if (connection.stream) void connection.context.close().catch(() => {});
}
owned.current = null;
analyserRef.current = null;
};
}, [audioRef, mediaStream, analyserNode]);
useEffect(() => {
if (owned.current) {
owned.current.analyser.fftSize = size;
owned.current.analyser.smoothingTimeConstant = smoothingValue;
}
}, [size, smoothingValue]);
return { analyserRef, node, ready: node !== null, error, connect };
}
type AudioVisualizerVariant =
| 'radial'
| 'halo'
| 'bars'
| 'wave'
| 'silk'
| 'orb'
| 'led'
| 'scope';
type AudioVisualizerTheme = 'classic' | 'acoustic' | 'neon' | 'sunset' | 'progress';
type VisualizerPalette = {
name: string;
getBarStyle: (
index: number,
total: number,
progress: number,
amplitude: number,
frequencyHz: number,
) => string;
};
const VISUALIZER_THEMES: Record<AudioVisualizerTheme, VisualizerPalette> = {
classic: {
name: 'Theme monochrome',
getBarStyle: () => '', // Theme-aware ink is resolved by the canvas renderer.
},
acoustic: {
name: '7-Zone Acoustic Color-Coding (20Hz–20kHz)',
getBarStyle: (_i, _total, _progress, amp, freqHz) => {
const zone = getAcousticZoneForHz(freqHz);
const lightness = 50 + Math.min(34, amp * 28);
return `hsla(${zone.hue}, 92%, ${lightness}%, ${0.48 + Math.min(0.52, amp * 0.55)})`;
},
},
progress: {
name: 'Radial Progress Tracker',
getBarStyle: () => '', // Theme-aware progress ink is resolved by the canvas renderer.
},
neon: {
name: 'Cyber Cyan & Violet',
getBarStyle: (i, total, _progress, amp) => {
const hue = 180 + (i / total) * 110;
const lightness = 50 + amp * 20;
return `hsla(${hue}, 95%, ${lightness}%, ${0.6 + amp * 0.4})`;
},
},
sunset: {
name: 'Amber Glow',
getBarStyle: (i, total, _progress, amp) => {
const hue = 15 + (i / total) * 45;
const lightness = 52 + amp * 20;
return `hsla(${hue}, 95%, ${lightness}%, ${0.55 + amp * 0.45})`;
},
},
};
function getVisualBandEnergy(data: Uint8Array, lowHz: number, highHz: number, sampleRate: number) {
if (!data.length || lowHz >= sampleRate / 2) return 0;
const nyquist = sampleRate / 2;
const binCount = data.length;
const exactLowBin = Math.max(0.5, (lowHz / nyquist) * binCount);
const exactHighBin = Math.min(
binCount - 1,
Math.max(exactLowBin + 0.5, (highHz / nyquist) * binCount),
);
const lowBin = Math.max(1, Math.floor(exactLowBin));
const highBin = Math.min(binCount - 1, Math.ceil(exactHighBin));
let sum = 0;
let peak = 0;
let weightSum = 0;
for (let b = lowBin; b <= highBin; b++) {
let weight = 1.0;
if (b === lowBin && exactLowBin > lowBin) weight = 1 - (exactLowBin - lowBin);
else if (b === highBin && exactHighBin < highBin) weight = 1 - (highBin - exactHighBin);
weight = Math.max(0.15, weight);
const val = data[b];
sum += val * weight;
if (val > peak) peak = val;
weightSum += weight;
}
const avg = weightSum > 0 ? sum / weightSum : 0;
const rawNorm = (peak * 0.65 + avg * 0.35) / 255;
const centerHz = (lowHz + highHz) * 0.5;
let eqComp = 1.0;
if (centerHz <= 60) eqComp = 0.9;
else if (centerHz <= 250) eqComp = 0.98;
else if (centerHz <= 500) eqComp = 1.08;
else if (centerHz <= 2000) eqComp = 1.22;
else if (centerHz <= 4000) eqComp = 1.36;
else if (centerHz <= 6000) eqComp = 1.5;
else eqComp = 1.68;
const gated = Math.max(0, rawNorm - 0.03);
return gated ** 1.12 * eqComp;
}
export type {
AudioAnalyzerOptions,
AudioVisualizerTheme,
AudioVisualizerVariant,
VisualizerPalette,
};
export {
ACOUSTIC_ZONES,
clamp,
getAcousticZoneForHz,
getAudioBandEnergy,
getVisualBandEnergy,
useAudioAnalyzer,
VISUALIZER_THEMES,
};
import { cn } from '@/lib/utils';
type ClassValue = string | false | null | undefined;
type PartClassValue<State> = ClassValue | ((state: State) => ClassValue);
/** Composes static class names and UI-SDK state class functions into a single `className` prop. */
export function partClass<State>(...parts: PartClassValue<State>[]) {
if (parts.some((part) => typeof part === 'function')) {
return (state: State) =>
cn(...parts.map((part) => (typeof part === 'function' ? part(state) : part)));
}
return cn(...(parts as ClassValue[]));
}
export const surfacePadding = 'p-1 [--surface-padding:1.5rem] [--concentric-inset:0.25rem]';
export const surfaceRegionInset = 'p-[calc(var(--surface-padding,1rem)-0.5rem)]';
export const surfaceHeaderRadius = 'rounded-t-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
export const surfaceFooterRadius = 'rounded-b-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
/** Concentric inner radius (`outer - inset`); set `[--concentric-inset:0.125rem]` on `p-0.5` rails (defaults to `0.25rem` for `p-1`). */
export const concentricRadius =
'rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))]';
export const surfaceBodyPadding =
'py-[max(0px,calc(var(--surface-padding,1rem)-1rem))] has-[>[data-slot=list]:not([data-variant=plain])]:p-0 has-[>[data-slot=list-items-container]]:p-0';
export type StandardControlSize = 'xs' | 'sm' | 'md' | 'lg';
/** Standard control heights (`28px / 32px / 40px / 48px`) for buttons, inputs, selects, tabs, and sliders. */
export const controlHeights = {
xs: 'h-7',
sm: 'h-8',
md: 'h-10',
lg: 'h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard minimum control heights (`28px / 32px / 40px / 48px`) for expandable controls and menu items. */
export const controlMinHeights = {
xs: 'min-h-7',
sm: 'min-h-8',
md: 'min-h-10',
lg: 'min-h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard control text sizes (`xs / xs / sm / base`) paired with `StandardControlSize`. */
export const controlTextSizes = {
xs: 'text-xs',
sm: 'text-xs',
md: 'text-sm',
lg: 'text-base',
} as const satisfies Record<StandardControlSize, string>;
/** Compact control heights (`1.25rem / 1.3rem / 1.625rem / 1.75rem`), one step smaller than standard, for switches and compact controls. */
export const compactControlHeights = {
xs: 'h-[1.3rem]',
sm: 'h-[1.4rem]',
md: 'h-[1.5rem]',
lg: 'h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Compact minimum control heights (`1rem / 1.25rem / 1.5rem / 1.75rem`) for badges and tooltips. */
export const compactControlMinHeights = {
xs: 'min-h-[1.3rem]',
sm: 'min-h-[1.4rem]',
md: 'min-h-[1.5rem]',
lg: 'min-h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Universal keyboard focus + invalid ring/border styles shared across controls. */
export const focusRing =
'touch-manipulation outline-none focus-visible:border-ring/30 transition-ring focus-visible:ring-3 focus-visible:ring-ring/15 focus-visible:brightness-[0.97] dark:focus-visible:brightness-[1.15] has-[:focus-visible]:border-ring/30 has-[:focus-visible]:ring-3 has-[:focus-visible]:ring-ring/15 has-[:focus-visible]:brightness-[0.97] dark:has-[:focus-visible]:brightness-[1.15] data-active:border-ring/30 data-active:ring-3 data-active:ring-ring/15 data-active:brightness-[0.97] dark:data-active:brightness-[1.15] data-open:border-ring/30 data-open:ring-3 data-open:ring-ring/15 data-open:brightness-[0.97] dark:data-open:brightness-[1.15] data-disabled:cursor-not-allowed data-disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/25 data-invalid:border-destructive data-invalid:ring-3 data-invalid:ring-destructive/25 has-[[data-invalid]]:border-destructive has-[[data-invalid]]:ring-3 has-[[data-invalid]]:ring-destructive/25 group-aria-invalid/control:border-destructive group-aria-invalid/control:ring-3 group-aria-invalid/control:ring-destructive/25 group-data-invalid/control:border-destructive group-data-invalid/control:ring-3 group-data-invalid/control:ring-destructive/25 group-has-[input[aria-invalid=true]]/control:border-destructive group-has-[input[aria-invalid=true]]/control:ring-3 group-has-[input[aria-invalid=true]]/control:ring-destructive/25 hover:brightness-[0.97] dark:hover:brightness-[1.15]';
/** Shared sliding highlight indicator base (pointer-safe, concentric inner radius inside rounded-lg containers, 200ms transition). */
export const slidingHighlight =
'pointer-events-none -z-10 rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))] bg-primary/10 [clip-path:inset(0px_round_max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem))))] transition-[transform,width,height,opacity] duration-200 ease-out motion-reduce:transition-none';
export const textFieldSurfaces = {
filled: 'border-input bg-card text-card-foreground',
outline: 'border-input bg-transparent text-foreground dark:bg-transparent',
ghost: 'border-transparent bg-muted text-foreground shadow-none',
underline:
'rounded-none border-0 border-b-2 border-input bg-transparent px-0 text-foreground shadow-none focus-visible:border-ring focus-visible:ring-0 aria-invalid:ring-0 data-invalid:ring-0 dark:bg-transparent',
} as const;
export const textFieldUnderlineMotion =
'border-transparent! bg-origin-border bg-bottom bg-no-repeat [--underline-color:var(--primary)] [background-image:linear-gradient(var(--underline-color),var(--underline-color)),linear-gradient(var(--input),var(--input))] [background-size:0%_2px,100%_2px] focus:[background-size:100%_2px,100%_2px] aria-invalid:[--underline-color:var(--destructive)] data-invalid:[--underline-color:var(--destructive)] transition-[border-color,background-color,box-shadow,filter,background-size] duration-200 motion-reduce:transition-none';
/** Generic balanced icon & floating-label layout tokens shared across all text-field sizes. */
export const textFieldLayout = {
icon: 'size-4',
iconStart: 'start-3',
iconEnd: 'end-3',
padStart: 'ps-9',
padEnd: 'pe-9',
underlinePadStart: 'ps-7',
underlinePadEnd: 'pe-7',
floatingStart: 'start-2.5',
floatingWithIcon: 'start-8',
floatingUnderlineIcon: 'start-6',
} as const;
export const textFieldLabelSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
/** Clamps per-grapheme wave delay (ms) so total staggering stays within 300ms. */
export function clampWaveDelay(waveDelay: number, count: number): number {
return Math.max(
0,
Math.min(Number.isFinite(waveDelay) ? waveDelay : 24, 80, 300 / Math.max(1, count - 1)),
);
}
/** Shared scale/color transition for floating labels inside a `group/field` wrapper. */
export const textFieldLabelMotion =
'inline-block origin-left backdrop-blur-xs transition-[scale,color] duration-200 ease-out group-has-[input:focus]/field:scale-85 group-has-[input:not(:placeholder-shown)]/field:scale-85 rtl:origin-right motion-reduce:transition-none';
/** Resolves start/end padding for a text field when a leading or trailing icon is present. */
export function getTextFieldIconPadding(iconPosition: 'start' | 'end', underline: boolean): string {
if (iconPosition === 'start') {
return underline ? textFieldLayout.underlinePadStart : textFieldLayout.padStart;
}
return underline ? textFieldLayout.underlinePadEnd : textFieldLayout.padEnd;
}
/** Shared per-grapheme ripple transition for wave labels inside a `group/field` wrapper. */
export const textFieldWaveMotion =
'inline-block origin-left backdrop-blur-xs transition-[translate,scale,color] duration-200 ease-out group-has-[input:focus]/field:-translate-y-5 group-has-[input:focus]/field:scale-85 group-has-[input:focus]/field:text-primary group-has-[input:not(:placeholder-shown)]/field:-translate-y-5 group-has-[input:not(:placeholder-shown)]/field:scale-85 group-has-[input[aria-invalid=true]]/field:text-destructive rtl:origin-right motion-reduce:transition-none';