useLevel
Read a meter source into Svelte state at a low rate, for labels and conditional UI.
Meters paint every frame without Svelte state. When you need the level in your markup, for a label or to show a warning, useLevel samples the source a few times a second.
$ pnpm dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-level.json$ npx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-level.json$ yarn dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-level.json$ bunx --bun shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-level.jsonUsage
<script lang="ts">
import { useLevel } from "#lib/hooks/use-level.svelte.js";
const level = useLevel(() => analyser.meter);
</script>
{#if level.zone === "clip"}
<p>Turn your microphone down.</p>
{/if}Call it during component setup. The source and the options can be getters, such as () => ({ intervalMs }). The returned fields are getters too: read them from the object, such as level.peakDb. Destructuring reads them once and loses updates.
Options
| Prop | Type | Default |
|---|---|---|
intervalMs How often the state updates. | number | 250 |
channel A channel index, or the loudest channel. | number | "max" | "max" |
zones Zones used to compute zone. | MeterZone[] | DEFAULT_ZONES |
enabled Pause sampling. | boolean | true |
Returns
| Prop | Type | Default |
|---|---|---|
peakDb Peak level in dBFS. -Infinity until the first frame. | number | — |
rmsDb RMS level in dBFS, when the source measures it. | number | undefined | — |
zone The zone of peakDb. | "ok" | "warn" | "clip" | — |