# Meter

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

**In Vue**

```tsx
<script lang="ts" setup>
import { onBeforeUnmount, onMounted } from "vue";
import Meter from "@/components/audio-ui/meter/Meter.vue";
import { createSimulatedLevels } from "@/lib/simulated-levels";

// The marks of a dBFS scale, down to the floor.
const scale = [6, 0, -6, -12, -20, -30, -40, -60];

const simulated = createSimulatedLevels(2);
let stop: (() => void) | undefined;
onMounted(() => {
  stop = simulated.run();
});
onBeforeUnmount(() => stop?.());
</script>

<template>
  <Meter
    aria-label="Stereo output"
    :marks="scale"
    :source="simulated.source"
    :warn-threshold="-12"
  />
</template>
```

**In Svelte**

```tsx
<script lang="ts">
import Meter from "$lib/components/audio-ui/meter/Meter.svelte";
import { createSimulatedLevels } from "@/lib/simulated-levels";

// The marks of a dBFS scale, down to the floor.
const scale = [6, 0, -6, -12, -20, -30, -40, -60];

const simulated = createSimulatedLevels(2);
$effect(() => simulated.run());
</script>

<Meter
  aria-label="Stereo output"
  marks={scale}
  source={simulated.source}
  warnThreshold={-12}
/>
```

**In Web**

```tsx
import "@/components/audio-ui/meter/web";
import { createSimulatedLevels } from "@/lib/simulated-levels";

// The marks of a dBFS scale, down to the floor.
const SCALE = [6, 0, -6, -12, -20, -30, -40, -60];

const channel = (index) => `
      <audio-ui-meter-channel aria-label="Stereo output ${index + 1}" index="${index}">
        <audio-ui-meter-indicator></audio-ui-meter-indicator>
        <audio-ui-meter-peak></audio-ui-meter-peak>
      </audio-ui-meter-channel>`;

const mark = (level) => `
      <audio-ui-meter-mark value="${level}">
        <span aria-hidden="true" data-orientation="vertical" data-slot="meter-mark-tick"></span>
        <span data-slot="meter-mark-label">${level}</span>
      </audio-ui-meter-mark>`;

/** Draws the meter into `element`, and returns what takes it away. Its look is the meter's sheet, on its parts and attributes. */
export function meterWebDemo(element) {
  element.innerHTML = `
    <audio-ui-meter aria-label="Stereo output" data-marks="labels" data-size="default" scale="iec" warn-threshold="-12">${channel(0)}${channel(1)}${SCALE.map(mark).join("")}
    </audio-ui-meter>`;
  const simulated = createSimulatedLevels(2);
  const meter = element.querySelector("audio-ui-meter");
  if (meter) {
    meter.source = simulated.source;
  }
  const stop = simulated.run();
  return () => {
    stop();
    element.innerHTML = "";
  };
}
```

**In React**

```tsx
import { Meter } from "@/components/audio-ui/meter";
import { useSimulatedLevels } from "@/hooks/use-simulated-levels";

// The marks of a dBFS scale, down to the floor.
const SCALE = [6, 0, -6, -12, -20, -30, -40, -60];

export function MeterSizeDefaultDemo() {
  const source = useSimulatedLevels(2);
  return (
    <Meter
      aria-label="Stereo output"
      marks={SCALE}
      source={source}
      warnThreshold={-12}
    />
  );
}
```

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.

**In Vue, Svelte and Web**

The meter's behavior is one file, the primitive, written on the UI SDK kernel and copied into your project. Each framework renders it with a thin adapter that you also own. The levels, the clip and warning zones, the scales and the peak marks are the same in all four, and one suite of tests runs against each adapter.

## Overview

- **Value:** one dB reading per channel (stereo is `[left, right]`), from the `value` prop or a live [`source`](#feeding-real-levels). 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](#feeding-real-levels), 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](https://ui-sdk.dev) 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`.

**In React**

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

**In React**

**CLI**

The styled component, with size variants and theme styles:

```bash
npx shadcn@latest add @audio-ui/meter
```

Or the primitive alone, to style yourself:

```bash
npx 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:

```bash
npx shadcn@latest add @audio-ui/primitives-css
```

**In Vue, Svelte and Web**

**CLI**

The [CLI](/docs/cli) finds your framework in `package.json` and writes the styled component with what draws it: the primitive, its adapter, `primitive.ts` and the sheet of your style, with an index to import once. It installs the kernel's packages:

```bash
npx @audio-ui/cli add meter
```

Or the primitive alone, to style yourself:

```bash
npx @audio-ui/cli add meter --headless
```

**manual**

### 1. The kernel

**React**

```bash
npm install @ui-sdk/core@0.1.0-beta.14 @ui-sdk/react@0.1.0-beta.14
```

**Vue**

```bash
npm install @ui-sdk/core@0.1.0-beta.14 @ui-sdk/vue@0.1.0-beta.14 vue
```

**Svelte**

```bash
npm install @ui-sdk/core@0.1.0-beta.14 @ui-sdk/svelte@0.1.0-beta.14 svelte
```

**JavaScript**

```bash
npm install @ui-sdk/core@0.1.0-beta.14 @ui-sdk/web@0.1.0-beta.14
```

### 2. The primitive

The same three files for every framework: `meter.ts`, the meter's behavior written on the kernel's helpers; `levels.ts`, how a level in dB is placed along the meter; and `primitive.ts`, the little every primitive shares. Copy them into `components/audio-ui/` (`src/lib/components/audio-ui/` in Svelte).

<ItemFiles name="meter-react" to={3} />

### 3. The adapter

Your framework's few parts, over the primitive. They import it by a relative path, from the same folder, so keep the files as shown, or update the path.

**React**

<ItemFiles name="meter-react" from={3} />

**Vue**

<ItemFiles name="meter-vue" from={3} />

**Svelte**

A component per part, and an `index.ts` that gathers them. Svelte keeps its files under `src/lib`, so the primitive goes in `src/lib/components/audio-ui/` too.

<ItemFiles name="meter-svelte" from={3} />

**JavaScript**

Import it once, and it registers the `audio-ui-meter` tags.

<ItemFiles name="meter-web" from={3} />

### 4. The styles

Optional, and the same for every framework: the anatomy of the primitives, drawn flat and square, in the look of the UI SDK docs. It reads the tokens of the UI SDK stylesheet (`--ui-*`) when the page has it, and falls back to its own. Every rule is in the `ui-sdk` layer, so a rule of yours outside the layer wins.

<ItemFiles name="primitives-css" />

Import it once.

**In React**

### 5. The styled component

Optional: size variants and theme styles over the primitive.

```bash
npm install class-variance-authority
```

<ItemFiles name="meter" />

**In Vue, Svelte and Web**

### 5. The styled component

Optional: the meter as the registry draws it in React, with no classes and no Tailwind. Its look is one sheet of plain CSS on its parts, a sheet for each style (`nova`, `vega`, `maia`, `lyra`, `mira`, `luma`, `rhea`, `sera`). Copy the sheet of your style into your project, with the theme's tokens when the page has no shadcn theme.

The [CLI](/docs/cli) writes the component, its adapter, the sheet and an index to import once:

```bash
npx @audio-ui/cli add meter
```

By hand:

```html
<link rel="stylesheet" href="/css/theme.css" />
<link rel="stylesheet" href="/css/nova/meter.css" />
```

Both are served at `https://www.audio-ui.dev/css/`.

**Vue**

One component over the adapter, with the props of the React meter.

<ItemFiles name="meter-element-vue" />

**Svelte**

One component over the adapter, with the props of the React meter.

<ItemFiles name="meter-element-svelte" />

**JavaScript**

The custom elements take the same sheet. Write the parts the example above writes, and set `data-size` and `data-marks` on `audio-ui-meter`, as the styled component does.

**agent**

Paste this prompt to your agent. It does the rest: it installs the skill, adds the component and wires it to your audio.

```text
Install the audio/ui skill with `npx skills add ouestlabs/audio-ui`, then follow it to add the meter from audio/ui to my project and wire it to my audio code. Read the docs at https://www.audio-ui.dev/llms.txt first.
```

To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents).

## Usage

**In React**

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

**Static levels:**

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

**With a peak-hold mark:**

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

**In React**

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.

**React**

```tsx
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.

**Vue**

```vue
<script setup lang="ts">
import { Meter } from "@/components/audio-ui/meter/vue";

defineProps<{ levels: number[] }>();
</script>

<template>
  <Meter.Root aria-label="Output" class="flex h-40 gap-1" :value="levels" :warn-threshold="-6">
    <template #default="{ state }">
      <Meter.Mark :value="0" />
      <Meter.Channel
        v-for="index in state.channelCount"
        :key="index"
        :aria-label="`Channel ${index}`"
        :index="index - 1"
        class="relative w-4 bg-muted"
      >
        <Meter.Indicator class="absolute bottom-0 bg-primary" />
        <Meter.Peak class="absolute h-0.5 w-full bg-foreground" />
      </Meter.Channel>
    </template>
  </Meter.Root>
</template>
```

**Svelte**

```svelte
<script lang="ts">
  import { Meter } from "$lib/components/audio-ui/meter/svelte";

  let { levels }: { levels: number[] } = $props();
</script>

<Meter.Root aria-label="Output" class="flex h-40 gap-1" value={levels} warnThreshold={-6}>
  {#snippet children(state)}
    <Meter.Mark value={0} />
    {#each Array.from({ length: state.channelCount }, (_, i) => i) as index (index)}
      <Meter.Channel aria-label={`Channel ${index + 1}`} class="relative w-4 bg-muted" {index}>
        <Meter.Indicator class="absolute bottom-0 bg-primary" />
        <Meter.Peak class="absolute h-0.5 w-full bg-foreground" />
      </Meter.Channel>
    {/each}
  {/snippet}
</Meter.Root>
```

With the latest SvelteKit, import through `#lib` in place of `$lib`: `#lib/components/audio-ui/meter/svelte`.

**JavaScript**

```html
<audio-ui-meter aria-label="Output" value="[-30,-12]" warn-threshold="-6">
  <audio-ui-meter-mark value="0"></audio-ui-meter-mark>
  <audio-ui-meter-channel index="0" aria-label="Left">
    <audio-ui-meter-indicator></audio-ui-meter-indicator>
    <audio-ui-meter-peak></audio-ui-meter-peak>
  </audio-ui-meter-channel>
  <audio-ui-meter-channel index="1" aria-label="Right">
    <audio-ui-meter-indicator></audio-ui-meter-indicator>
    <audio-ui-meter-peak></audio-ui-meter-peak>
  </audio-ui-meter-channel>
</audio-ui-meter>

<script type="module">
  import "./audio-ui/meter/web.ts";
</script>
```

Each part binds a microtask after it connects, all together. The channels are written in the markup, so their number does not follow a live source.

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.

```ts
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.

**In React**

## 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):

```ts
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.

```bash
npx shadcn@latest add @audio-ui/use-audio-levels
```

```tsx
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](/docs/guides/analysis).

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

## API reference

**In React**

### Registry component

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

#### Value and state

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `number[]` |  | Level (dB) per channel; array length is the channel count. |
| `peak` | `number[]` |  | Peak-hold level per channel. Timing and decay live outside the primitive. |
| `source` | `MeterSource` |  | A live signal painted outside React; takes precedence over `value` and `peak`. |
| `min` | `number` | `-60` | Minimum of the dB range. |
| `max` | `number` | `6` | Maximum of the dB range. |
| `clipThreshold` | `number` | `0` | Level at or above which a channel is clipping. |
| `orientation` | `"vertical" \| "horizontal"` | `"vertical"` | Bar direction. |
| `format` | `Intl.NumberFormatOptions` | `one decimal` | Formats each level for `Meter.Value` and the channels' `aria-valuetext`. Defaults to one decimal. |
| `aria-label` | `string` |  | Accessible name for the meter group and its channels. |

#### Layout and display

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `size` | `"sm" \| "default" \| "lg"` | `"default"` | Size variant (sets the meter height). |
| `peakMarks` | `"visible" \| "hidden"` | `"visible"` | Shows or hides the peak-hold mark per channel. |
| `marks` | `number[]` |  | Levels graduated along the meter, each with a tick and its label, such as `[6, 0, -6, -12, -20, -30, -40, -60]`. |
| `scale` | `"linear" \| "iec" \| (level) => number` | `"iec"` | How levels are spread along the length: the registry element starts on the IEC scale of digital peak meters. |
| `className` | `string` |  | Additional CSS classes. |

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).

| Option | Type | Default | |
| --- | --- | --- | --- |
| `value` | `number[]` | | The level of each channel, in dB. Its length is the channel count. |
| `peak` | `number[]` | | 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`, `max` | `number` | `-60`, `6` | The 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. |
| `clipThreshold` | `number` | `0` | The level at or above which a channel is clipping. |
| `warnThreshold` | `number` | | The level at or above which a channel is in its warning zone, below the clip threshold. Unset, there is no warning zone. |
| `format`, `locale` | `Intl.NumberFormat` options, a locale | one decimal | How 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

**In React, Vue and Svelte**

| Part | Element | Props |
| --- | --- | --- |
| `Meter.Channel` | `div` | `getAriaValueText: value`, `index: key` |
| `Meter.Indicator` | `div` | `index: [object Object]`, `value: [object Object]` |
| `Meter.Label` | `span` | `index: [object Object]`, `value: [object Object]` |
| `Meter.Mark` | `div` | `value: number` |
| `Meter.Peak` | `div` | `index: [object Object]`, `value: [object Object]` |
| `Meter.Root` | `div` |  |
| `Meter.Track` | `div` |  |
| `Meter.Value` | `span` | `index: [object Object]`, `value: [object Object]` |

**In Web**

The tags the web adapter registers: the inputs inside a part are made for you.

`audio-ui-meter`, `audio-ui-meter-channel`, `audio-ui-meter-indicator`, `audio-ui-meter-label`, `audio-ui-meter-mark`, `audio-ui-meter-peak`, `audio-ui-meter-track`, `audio-ui-meter-value`

### Events

| React and Svelte | Vue | Web |
| --- | --- | --- |

**In React**

## Examples

### Mixing console

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

```tsx
import { useEffect, useState } from "react";
import { MixerView } from "@/components/audio-ui/mixer-view";
import { useArrangement } from "@/hooks/use-arrangement";
import { useArrangementEngine } from "@/hooks/use-arrangement-engine";
import { useTrackAutomation } from "@/hooks/use-track-automation";
import { usePlaySwitch } from "@/hooks/use-play-switch";
import {
  type Arranged,
  type ArrangementTrack,
  UNITY_MIX,
} from "@/lib/arrangement";
import type { RecordingSource } from "@/lib/clip-player";
import {
  DEMO_TEMPO,
  type DemoSourceName,
  renderDemoSource,
} from "@/lib/demo-sound";
import { libraryDevice } from "@/lib/device-library";
import { webAudio } from "@/lib/web-audio";

/** The tracks, each playing one of the demo's sounds round and round, at a level that leaves the main track under 0 dB. */
const SOUNDS: {
  gain: number;
  id: string;
  name: string;
  pan: number;
  send: number;
  source: DemoSourceName;
}[] = [
  { gain: 0.4, id: "kick", name: "Kick", pan: 0, send: 0, source: "kick" },
  {
    gain: 0.4,
    id: "groove",
    name: "Groove",
    pan: -0.25,
    send: 0.35,
    source: "groove",
  },
  {
    gain: 0.25,
    id: "drone",
    name: "Drone",
    pan: 0.3,
    send: 0.5,
    source: "chord",
  },
];

const REVERB = "return-1";

const reverb = libraryDevice("audioui.reverb");

const TRACKS: ArrangementTrack[] = SOUNDS.map(
  ({ gain, id, name, pan, send }, index) => ({
    color: index,
    id,
    mix: { ...UNITY_MIX, color: index, gain, pan },
    name,
    // A share of the groove and of the drone goes to the reverb.
    sends: send > 0 ? { [REVERB]: send } : undefined,
  })
);

const RETURNS: ArrangementTrack[] = [
  {
    color: 0,
    devices: reverb
      ? [
          {
            device: "audioui.reverb",
            id: "reverb",
            state: reverb.device.defaults(),
          },
        ]
      : [],
    id: REVERB,
    name: "A Reverb",
  },
];

/** The metronome stays off: the loops are the only thing that plays. */
const NO_METRONOME = { on: false, rhythm: "auto" } as const;

/** The clip of a track: its sound, round and round for the whole length. */
function loopClip(
  id: string,
  name: string,
  own: number,
  length: number
): Arranged {
  return {
    id: `clip-${id}`,
    loop: [0, own],
    name,
    recording: id,
    sourceLength: own,
    track: id,
    value: { fadeIn: 0, fadeOut: 0, length, offset: 0, start: 0 },
  };
}

/**
 * A mixing console over an arrangement: a channel for each track with its
 * pan, its sends, its fader, its meter and its peak, Solo and Mute, then a
 * return track, and the main track, which stays in sight at the right while
 * the channels scroll. Play the loops: every meter reads the real signal of
 * its channel. It is the same view a workstation shows under its tracks.
 */
export function BlockMixer() {
  const arrangement = useArrangement({
    duration: 1,
    initialReturns: RETURNS,
    initialTracks: TRACKS,
    tempo: DEMO_TEMPO,
  });
  const { dispatch, doc } = arrangement;
  const automation = useTrackAutomation({ dispatch, tracks: doc.tracks });
  const { playing } = usePlaySwitch();
  const [selected, setSelected] = useState<string | null>(null);

  // The sounds, as the tracks' recordings, and a clip on each that loops it.
  const [sources, setSources] = useState<ReadonlyMap<string, RecordingSource>>(
    () => new Map()
  );
  useEffect(() => {
    const context = webAudio.getContext();
    if (!context) {
      return;
    }
    let cancelled = false;
    Promise.all(
      SOUNDS.map(({ source }) => renderDemoSource(source, context.sampleRate))
    ).then((buffers) => {
      if (cancelled) {
        return;
      }
      const length = Math.max(...buffers.map((buffer) => buffer.duration));
      setSources(
        new Map(
          SOUNDS.map(({ id }, index) => {
            const buffer = buffers[index];
            return [
              id,
              {
                channels: Array.from(
                  { length: buffer?.numberOfChannels ?? 0 },
                  (_, channel) =>
                    buffer?.getChannelData(channel) ?? new Float32Array()
                ),
                sampleRate: buffer?.sampleRate ?? context.sampleRate,
              },
            ];
          })
        )
      );
      dispatch({
        commands: [
          { duration: length, type: "set-duration" },
          { loop: { on: true, range: [0, length] }, type: "set-loop" },
          ...SOUNDS.flatMap(({ id, name }, index) => [
            { id: `clip-${id}`, type: "remove-clip" } as const,
            {
              clip: loopClip(
                id,
                name,
                buffers[index]?.duration ?? length,
                length
              ),
              type: "add-clip",
            } as const,
          ]),
        ],
        type: "batch",
      });
    });
    return () => {
      cancelled = true;
    };
  }, [dispatch]);

  const engine = useArrangementEngine({
    doc,
    metronome: NO_METRONOME,
    overridden: automation.overridden,
    recordings: sources,
  });
  const { engine: running, play, stop } = engine;
  const ready = running !== null && sources.size > 0;
  // The play switch of the preview's bar plays the loops, from their start.
  useEffect(() => {
    if (!ready) {
      return;
    }
    if (playing) {
      play(0);
    } else {
      stop();
    }
  }, [play, playing, ready, stop]);

  return (
    <div className="rounded-xl h-96 w-full min-w-0 overflow-hidden border bg-card">
      <MixerView
        arrangement={arrangement}
        engine={engine}
        onMix={automation.changeMix}
        onSelectTrack={setSelected}
        overridden={automation.overridden}
        selectedTrack={selected}
      />
    </div>
  );
}
```

### Needle meter

For a dial instead of a bar, see [Needle meter](/docs/components/base/needle-meter): a VU meter to the standard, fed by the same `source`.

