useAudioAnalyser
Meter and visual frame sources from a MediaStream, media element or AudioNode.
useAudioAnalyser connects any audio to audiocn-svelte's meters and visualizers. It measures peak and RMS per channel and reduces the spectrum to frequency bands, and only runs while a component is subscribed.
$ pnpm dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-analyser.json$ npx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-analyser.json$ yarn dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-analyser.json$ bunx --bun shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-analyser.jsonUsage
<script lang="ts">
import { BarVisualizer } from "#lib/components/ui/bar-visualizer/index.js";
import { LevelMeter } from "#lib/components/ui/level-meter/index.js";
import { useAudioAnalyser } from "#lib/hooks/use-audio-analyser.svelte.js";
import { useMicrophone } from "#lib/hooks/use-microphone.svelte.js";
const microphone = useMicrophone({ enabled: true });
const analyser = useAudioAnalyser(() => microphone.stream, { channels: "stereo" });
</script>
<LevelMeter aria-label="Microphone" source={analyser.meter} />
<BarVisualizer aria-hidden="true" source={analyser.visual} />Call it during component setup. Pass the input as a getter, () => microphone.stream, so the analyser follows it. The options can be a getter too. meter and visual stay the same when the input changes, so components keep their subscription.
A media element can only be connected to Web Audio once. The hook remembers the connection, routes the element to the speakers through the context, and reuses it for every analyser.
Options
| Prop | Type | Default |
|---|---|---|
input What to analyse. | MediaStream | HTMLMediaElement | AudioNode | null | — |
fftSize Analyser FFT size. | number | 2048 |
smoothing Analyser smoothing constant, 0..1. | number | 0.3 |
bands Frequency bands per visual frame. | number | 32 |
minHz / maxHz Band range, spaced on a log scale. | number | 40 / 16000 |
historySize Entries in the level history ring. | number | 60 |
historyIntervalMs Time between history entries. | number | 50 |
intervalMs Minimum time between frames. 0 sends one every animation frame. | number | 0 |
channels stereo measures left and right separately. | "mono" | "stereo" | "mono" |
enabled Pause analysis without tearing it down. | boolean | true |
input is the first argument; the rest go in the options object.
Returns
| Prop | Type | Default |
|---|---|---|
meter Peak and RMS per channel. | FrameSource<MeterFrame> | — |
visual Bands, history, time-domain samples and peak. | FrameSource<VisualFrame> | — |
status idle with no input; suspended until the context resumes. | "idle" | "running" | "suspended" | — |
Frames are reused between updates to avoid allocating. Copy a frame if you need to keep it.