LabDAW

Meter

A level meter in decibels for one or more channels, with peak hold.

Shows audio levels for a stereo output, a channel strip or any multi-channel source. The registry component is written on the meter primitive, which installs with it: one bar per channel, a destructive color when a channel clips, and an optional peak-hold mark. The meter only displays levels: it takes no pointer or keyboard input, and no focus.

Overview

  • Value: one dB reading per channel (stereo is [left, right]), from the value prop or a live source. The number of readings sets the number of channels.
  • Peak hold: an optional peak level per channel places a peak-hold mark. The primitive has no clock: your source, Tone.js or another library computes the peak and its decay.
  • Clipping: channels at or above clipThreshold (default 0 dB) get data-clipping, to style a clip indicator.
  • Accessibility: each channel is a role="meter" with aria-valuenow, aria-valuemin, aria-valuemax and a value text in dB ("-6 dB"). It is not an aria-live region, so screen readers read the level when asked instead of announcing every update. aria-label names the group; with several channels, each is named "… 1", "… 2".

Installation

The primitives are built on the UI SDK kernel, in beta. Nothing of ours comes from npm: the primitive and its adapter are files you copy into your project and own, and the only packages are the kernel's. The commands name its version, @ui-sdk/*@0.1.0-beta.14.

The styled component, with sizes, a clip color and peak marks, is one command:

The styled component, with size variants and theme styles:

pnpm dlx shadcn@latest add @audio-ui/meter

Or the primitive alone, to style yourself:

pnpm dlx shadcn@latest add @audio-ui/meter-react

It writes the primitive, its adapter and primitive.ts into components/audio-ui/ and installs the kernel's packages and what each file imports. The optional styles are one more command:

pnpm dlx shadcn@latest add @audio-ui/primitives-css

Usage

import { Meter } from "@/components/audio-ui/meter";

Static levels:

<Meter value={[-9, -14]} />

With a peak-hold mark:

<Meter peak={[-4, -8]} value={[-9, -14]} />

The primitive alone, part by part:

A Root groups the channels. Each Channel has an index, the position of its level, and holds an Indicator that grows with the level, a Peak mark, a Value for the text and a Label that names it. Marks sit along the length, beside the channels. You write the channels yourself, one for each level.

The Root's content can read the meter's state, { channelCount, orientation }, so the channels follow the count of a live source: a function in React, the default slot in Vue, a snippet in Svelte.

import { Meter } from "@/components/audio-ui/meter/react";

export function Output({ levels }: { levels: number[] }) {
  return (
    <Meter.Root aria-label="Output" className="flex h-40 gap-1" value={levels} warnThreshold={-6}>
      {({ channelCount }) => [
        <Meter.Mark key="zero" value={0} />,
        ...Array.from({ length: channelCount }, (_, index) => (
          <Meter.Channel
            aria-label={`Channel ${index + 1}`}
            className="relative w-4 bg-muted"
            index={index}
            key={index}
          >
            <Meter.Indicator className="absolute bottom-0 bg-primary data-warning:bg-amber-400 data-clipping:bg-destructive" />
            <Meter.Peak className="absolute h-0.5 w-full bg-foreground" />
          </Meter.Channel>
        )),
      ]}
    </Meter.Root>
  );
}

The function is the Root's only child: put a Mark inside it, as here.

The Indicator is scaled from the bottom of a vertical meter and from the start of a horizontal one: give the Channel its size and position: relative, and the Indicator position: absolute with the color. The Peak is placed by bottom or left, and hidden while its channel has no peak. A Value takes the formatted level as its text, or a function of the state in React, a slot in Vue and a snippet in Svelte, which reads text, valueNow and the zone the level is in.

A live source

An engine updates levels 60 times a second, which is too often to render. Give the Root a source instead of value: the meter writes each frame straight to the elements of its channels, from one subscription for all of them, and the framework never renders for it.

let frame = { levels: [-30, -30], peaks: [-6, -6] };
const listeners = new Set<() => void>();

const source = {
  getSnapshot: () => frame,
  subscribe(listener: () => void) {
    listeners.add(listener);
    return () => listeners.delete(listener);
  },
};

// From the engine's frame loop:
frame = { levels: [-22.4, -19.8], peaks: [-6, -6] };
for (const listener of listeners) listener();

Any object with getSnapshot() returning { levels, peaks? } and subscribe(listener) works. The levels, the peak marks, aria-valuenow, aria-valuetext and the Value's text are written on each frame, and a clip is kept: the channel and its Indicator carry data-clipped from the first level at or above the clip threshold until a click on the meter clears it, as in a DAW. A source that changes its number of channels renders the channels again, and only then. In the web adapter, source is a property, not an attribute.

Feeding real levels

value and peak are plain props: fine for static or slowly changing levels, but a signal sampled 60 times a second would re-render React on every frame. For live audio, pass a source instead: the meter subscribes to it and writes each frame to the DOM, without a React render.

A source is any object with the shape of an external store, so you can bring your own (Tone.js, a worklet, a WebSocket):

interface MeterSource {
  getSnapshot: () => { levels: readonly number[]; peaks?: readonly number[] };
  subscribe: (listener: () => void) => () => void;
}

createSource from the primitive item (npx shadcn@latest add @audio-ui/primitive) makes one you push to. The use-audio-levels hook is one: it samples the RMS level of one AnalyserNode per channel every animation frame, how loud the signal sounds, and lets it fall back smoothly; its peak is the loudest sample, held a moment before it falls, so the mark shows how near the signal comes to clipping.

pnpm dlx shadcn@latest add @audio-ui/use-audio-levels
import { Meter } from "@/components/audio-ui/meter";
import { useAudioLevels } from "@/hooks/use-audio-levels";

// One analyser per channel, made once: a new array restarts the sampling.
const analysers = useMemo(() => {
  const analyser = ctx.createAnalyser();
  output.connect(analyser); // a tap: the analyser plays nothing
  return [analyser];
}, [ctx, output]);

const levels = useAudioLevels(analysers);

<Meter aria-label="Output" source={levels} />;

For a stereo meter, split the signal with a ChannelSplitter and give the hook one analyser per side. The hook and the other analysis tools are in Analysis.

To read the levels in React as well, for a numeric readout for example, use useSyncExternalStore(levels.subscribe, levels.getSnapshot).

API reference

Registry component

Meter accepts style props (size, peakMarks, marks, className) plus the props of the Meter primitive's Root.

Value and state

Props · 9

Layout and display

Props · 5

The Meter primitive that installs with it exposes Meter.Root (the group, whose children can be a function of its state, { channelCount, orientation }, to write one Meter.Channel for each channel), Meter.Channel (a role="meter"), Meter.Track, Meter.Indicator (the lit part), Meter.Peak (the peak-hold mark), Meter.Value (the formatted level), Meter.Mark (a graduation at a level) and Meter.Label. Channel parts expose data-orientation and data-clipping.

Options

Set on the Root, as props (an attribute in kebab case in the web adapter).

OptionTypeDefault
valuenumber[]The level of each channel, in dB. Its length is the channel count.
peaknumber[]The peak-hold level of each channel. Timing and decay live outside the primitive.
source{ getSnapshot, subscribe }A live signal, painted with no render. It takes precedence over value and peak.
min, maxnumber-60, 6The range, in dB.
orientation"vertical" or "horizontal""vertical"Which way the bars run.
scale"linear", "iec" or a function"linear"How levels are spread along the length. "iec" gives the top more room, as digital peak meters do; a function is any increasing curve of the level.
clipThresholdnumber0The level at or above which a channel is clipping.
warnThresholdnumberThe level at or above which a channel is in its warning zone, below the clip threshold. Unset, there is no warning zone.
format, localeIntl.NumberFormat options, a localeone decimalHow a level is written, for the Value and for aria-valuetext.

The Mark takes a value and sits along the length at its level. A Channel takes getAriaValueText(formatted, value, index) to announce its level in your own words, like "-6 dB". A function scale is a property: in the web adapter, set it from script.

States to style from

  • data-orientation on the Root, the channels, the Indicators, the Peaks and the Marks.
  • data-warning and data-clipping on a channel, its Indicator and its Peak, while its level is in the warning zone or at or above the clip threshold.
  • data-clipped on a channel and its Indicator, with a live source, from the first clip until a click on the meter.

Accessibility

Each channel is a role="meter" with aria-valuenow, aria-valuemin, aria-valuemax and an aria-valuetext that reads the level as a number with its unit, not as a share of the range. Name it with aria-label, or with a Label part inside it, which sets aria-labelledby. The Indicator, the Peak and the Value are hidden from assistive technology: the channel announces its own level.

Parts

Parts · 8

Events

Events · 0

Examples

Mixing console

Each channel's meter reads its real signal after the fader, and the master's reads both sides.

Needle meter

For a dial instead of a bar, see Needle meter: a VU meter to the standard, fed by the same source.

Built by Ouest Labs, the source code is available on GitHub.
RSS