# Waveform

> Draws audio: a seekable waveform with regions and markers, a live waveform that scrolls with the signal, and a bar visualizer.

**In Vue**

```tsx
<script lang="ts" setup>
import { ref } from "vue";
import { Waveform } from "@/components/audio-ui/waveform/vue";

const DURATION_SECONDS = 180;

// Stand-in for the peaks of a decoded audio file.
const PEAKS = Array.from({ length: 512 }, (_, index) => {
  const time = index / 512;
  const section =
    0.5 + 0.28 * Math.sin(time * 11 + 0.8) + 0.18 * Math.sin(time * 29);
  const beat = 0.7 + 0.3 * Math.abs(Math.cos(index * 0.26));
  const grain = Math.abs((Math.sin(index * 12.9898) * 43_758.5453) % 1);
  const level = section * beat * (0.45 + 0.55 * grain) + 0.04;
  return Math.round(Math.min(1, level) * 1000) / 1000;
});

function formatTime(seconds: number): string {
  const whole = Math.floor(seconds);
  return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`;
}

const describePosition = (value: number, duration: number) =>
  `${formatTime(value)} of ${formatTime(duration)}`;

const loop = ref<readonly [number, number]>([48, 96]);
</script>

<template>
  <div
    style="display: flex; flex-direction: column; gap: 0.5rem; width: 100%; min-width: 0"
  >
    <Waveform.Root
      :default-value="30"
      :duration="DURATION_SECONDS"
      :peaks="PEAKS"
    >
      <Waveform.Control
        aria-label="Track progress"
        :get-aria-value-text="describePosition"
      >
        <Waveform.Canvas />
        <Waveform.Region
          region="loop"
          :value="loop"
          @value-change="(next) => { loop = next; }"
        >
          <Waveform.RegionHandle
            aria-label="Loop start"
            edge="start"
            region="loop"
            :get-aria-value-text="formatTime"
          />
          <Waveform.RegionHandle
            aria-label="Loop end"
            edge="end"
            region="loop"
            :get-aria-value-text="formatTime"
          />
        </Waveform.Region>
        <Waveform.Marker :value="20">
          <span data-slot="waveform-marker-label">Verse</span>
        </Waveform.Marker>
        <Waveform.Marker :value="124">
          <span data-slot="waveform-marker-label">Chorus</span>
        </Waveform.Marker>
        <Waveform.Hover :format="formatTime" />
        <Waveform.Playhead />
        <Waveform.Thumb />
      </Waveform.Control>
    </Waveform.Root>
    <p
      style="color: var(--muted-foreground); font-size: 0.875rem; font-variant-numeric: tabular-nums"
    >
      Loop {{ formatTime(loop[0]) }} – {{ formatTime(loop[1]) }}
    </p>
  </div>
</template>
```

A live waveform, scrolling with a made-up voice:

```tsx
<script lang="ts" setup>
import { onBeforeUnmount, onMounted } from "vue";
import { createSource } from "@/components/audio-ui/primitive";
import { Waveform } from "@/components/audio-ui/waveform/vue";

/** A voice made up from a few slow waves: no microphone, no sound. */
function voiceAt(seconds: number) {
  const syllable = Math.max(0, Math.sin(seconds * 5.3)) ** 2;
  const breath = 0.55 + 0.45 * Math.sin(seconds * 0.9);
  return [Math.min(1, syllable * breath + 0.05)];
}

const level = createSource<ArrayLike<number>>([0]);

let frame = 0;
const tick = (now: number) => {
  level.set(voiceAt(now / 1000));
  frame = requestAnimationFrame(tick);
};
onMounted(() => {
  frame = requestAnimationFrame(tick);
});
onBeforeUnmount(() => cancelAnimationFrame(frame));
</script>

<!-- The waveform's root drawn as a live waveform: its sheet reads `data-variant`. -->
<template>
  <Waveform.Root
    aria-label="Voice"
    data-variant="live"
    role="img"
    :levels="level"
  >
    <Waveform.Canvas mode="scrolling" />
  </Waveform.Root>
</template>
```

**In Svelte**

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

const DURATION_SECONDS = 180;

// Stand-in for the peaks of a decoded audio file.
const PEAKS = Array.from({ length: 512 }, (_, index) => {
  const time = index / 512;
  const section =
    0.5 + 0.28 * Math.sin(time * 11 + 0.8) + 0.18 * Math.sin(time * 29);
  const beat = 0.7 + 0.3 * Math.abs(Math.cos(index * 0.26));
  const grain = Math.abs((Math.sin(index * 12.9898) * 43_758.5453) % 1);
  const level = section * beat * (0.45 + 0.55 * grain) + 0.04;
  return Math.round(Math.min(1, level) * 1000) / 1000;
});

function formatTime(seconds: number): string {
  const whole = Math.floor(seconds);
  return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`;
}

const describePosition = (value: number, duration: number) =>
  `${formatTime(value)} of ${formatTime(duration)}`;

let loop = $state<readonly [number, number]>([48, 96]);
</script>

<div
  style="display: flex; flex-direction: column; gap: 0.5rem; width: 100%; min-width: 0"
>
  <Waveform.Root defaultValue={30} duration={DURATION_SECONDS} peaks={PEAKS}>
    <Waveform.Control
      aria-label="Track progress"
      getAriaValueText={describePosition}
    >
      <Waveform.Canvas />
      <Waveform.Region
        onValueChange={(next) => {
          loop = next;
        }}
        region="loop"
        value={loop}
      >
        <Waveform.RegionHandle
          aria-label="Loop start"
          edge="start"
          getAriaValueText={formatTime}
          region="loop"
        />
        <Waveform.RegionHandle
          aria-label="Loop end"
          edge="end"
          getAriaValueText={formatTime}
          region="loop"
        />
      </Waveform.Region>
      <Waveform.Marker value={20}>
        <span data-slot="waveform-marker-label">Verse</span>
      </Waveform.Marker>
      <Waveform.Marker value={124}>
        <span data-slot="waveform-marker-label">Chorus</span>
      </Waveform.Marker>
      <Waveform.Hover format={formatTime} />
      <Waveform.Playhead />
      <Waveform.Thumb />
    </Waveform.Control>
  </Waveform.Root>
  <p
    style="color: var(--muted-foreground); font-size: 0.875rem; font-variant-numeric: tabular-nums"
  >
    Loop {formatTime(loop[0])} – {formatTime(loop[1])}
  </p>
</div>
```

**In Web**

```tsx
import "@/components/audio-ui/waveform/web";

const DURATION_SECONDS = 180;

// Stand-in for the peaks of a decoded audio file.
const PEAKS = Array.from({ length: 512 }, (_, index) => {
  const time = index / 512;
  const section =
    0.5 + 0.28 * Math.sin(time * 11 + 0.8) + 0.18 * Math.sin(time * 29);
  const beat = 0.7 + 0.3 * Math.abs(Math.cos(index * 0.26));
  const grain = Math.abs((Math.sin(index * 12.9898) * 43_758.5453) % 1);
  const level = section * beat * (0.45 + 0.55 * grain) + 0.04;
  return Math.round(Math.min(1, level) * 1000) / 1000;
});

function formatTime(seconds) {
  const whole = Math.floor(seconds);
  return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`;
}

/** Draws the waveform into `element`, and returns what takes it away. The canvas and the inputs are made for you. */
export function waveformWebDemo(element) {
  element.innerHTML = `
    <div style="display: flex; flex-direction: column; gap: 0.5rem; width: 100%; min-width: 0">
      <audio-ui-waveform default-value="30" duration="${DURATION_SECONDS}">
        <audio-ui-waveform-control aria-label="Track progress">
          <audio-ui-waveform-canvas></audio-ui-waveform-canvas>
          <audio-ui-waveform-region region="loop" value="[48,96]">
            <audio-ui-waveform-region-start region="loop"></audio-ui-waveform-region-start>
            <audio-ui-waveform-region-end region="loop"></audio-ui-waveform-region-end>
          </audio-ui-waveform-region>
          <audio-ui-waveform-marker value="20"><span data-slot="waveform-marker-label">Verse</span></audio-ui-waveform-marker>
          <audio-ui-waveform-marker value="124"><span data-slot="waveform-marker-label">Chorus</span></audio-ui-waveform-marker>
          <audio-ui-waveform-hover></audio-ui-waveform-hover>
          <audio-ui-waveform-playhead></audio-ui-waveform-playhead>
          <audio-ui-waveform-thumb></audio-ui-waveform-thumb>
        </audio-ui-waveform-control>
      </audio-ui-waveform>
      <p style="color: var(--muted-foreground); font-size: 0.875rem; font-variant-numeric: tabular-nums" data-loop>Loop 0:48 – 1:36</p>
    </div>`;
  const waveform = element.querySelector("audio-ui-waveform");
  const hover = element.querySelector("audio-ui-waveform-hover");
  const label = element.querySelector("[data-loop]");
  if (waveform) {
    waveform.peaks = PEAKS;
  }
  if (hover) {
    hover.format = formatTime;
  }
  const onRegion = (event) => {
    const [start, end] = event.detail.value;
    if (label) {
      label.textContent = `Loop ${formatTime(start)} – ${formatTime(end)}`;
    }
  };
  waveform?.addEventListener("regionchange", onRegion);
  return () => {
    waveform?.removeEventListener("regionchange", onRegion);
    element.innerHTML = "";
  };
}
```

**In React**

```tsx
import { useState } from "react";
import {
  Waveform,
  WaveformHover,
  WaveformMarker,
  WaveformRegion,
  WaveformRegionHandle,
} from "@/components/audio-ui/waveform";

const DURATION_SECONDS = 180;

// Stand-in for the peaks of a decoded audio file.
const VALUES = Array.from({ length: 512 }, (_, index) => {
  const time = index / 512;
  const section =
    0.5 + 0.28 * Math.sin(time * 11 + 0.8) + 0.18 * Math.sin(time * 29);
  const beat = 0.7 + 0.3 * Math.abs(Math.cos(index * 0.26));
  const grain = Math.abs((Math.sin(index * 12.9898) * 43_758.5453) % 1);
  const level = section * beat * (0.45 + 0.55 * grain) + 0.04;
  return Math.round(Math.min(1, level) * 1000) / 1000;
});

function formatTime(seconds: number): string {
  const whole = Math.floor(seconds);
  return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`;
}

const describePosition = (value: number, duration: number) =>
  `${formatTime(value)} of ${formatTime(duration)}`;

export function WaveformRegionDemo() {
  const [loop, setLoop] = useState<readonly [number, number]>([48, 96]);

  return (
    <div className="flex w-full min-w-0 flex-col gap-2">
      <Waveform
        aria-label="Track progress"
        defaultValue={30}
        duration={DURATION_SECONDS}
        getAriaValueText={describePosition}
        values={VALUES}
        variant="playhead"
      >
        <WaveformRegion onValueChange={setLoop} value={loop}>
          <WaveformRegionHandle
            aria-label="Loop start"
            edge="start"
            getAriaValueText={formatTime}
          />
          <WaveformRegionHandle
            aria-label="Loop end"
            edge="end"
            getAriaValueText={formatTime}
          />
        </WaveformRegion>
        <WaveformMarker value={20}>Verse</WaveformMarker>
        <WaveformMarker value={124}>Chorus</WaveformMarker>
        <WaveformHover format={formatTime} />
      </Waveform>
      <p className="text-muted-foreground text-sm tabular-nums">
        Loop {formatTime(loop[0])} – {formatTime(loop[1])}
      </p>
    </div>
  );
}
```

Components for drawing audio. `Waveform` shows a whole file and lets you scrub through it. `LiveWaveform` follows a signal as it plays. `BarVisualizer` turns that signal into a few bars you style in CSS. All three are written on the waveform primitive, which installs with them and works with any audio: decoded PCM samples, a microphone or a stream from your server.

**In Vue, Svelte and Web**

The waveform's behavior is a few files, the primitive, written on the UI SDK kernel and copied into your project. It shows the shape of audio, from `peaks` known upfront or from a live `levels` signal, and follows a playback position that can be seeked. Each framework renders it with a thin adapter that you also own, and one suite of tests runs against each adapter.

## Overview

- **Two kinds of data:** a file's shape is known in advance, so `Waveform` takes `values` (amplitudes from `0` to `1`, at any resolution). A live signal is not, so `LiveWaveform` and `BarVisualizer` take a [`source`](#live-signals) and follow it outside React.
- **Value:** `value` is the playback position, from `0` to `duration` (default `1`, a fraction; pass the track length in seconds to work in seconds). The primitive owns the seek position, not the audio: connect `onValueChange` to your own `<audio>` element.
- **Asymmetric shape:** give `values` the lowest and highest sample of each slice (`{ min, max }`) and the waveform is drawn asymmetric, as in a DAW. Plain amplitudes draw the same shape above and below the middle.
- **Part of the audio:** `range` shows only a stretch of the audio, such as a clip's window onto its source or a zoomed view. The playhead, seeking, hover, regions and markers follow that stretch. See [Showing part of the audio](#showing-part-of-the-audio).
- **Resolution:** the canvas draws as many bars as fit its width and keeps the loudest sample of each bar's slice, so detail holds at any size. Bars align to physical pixels, so their edges stay sharp at any pixel density or zoom. See [Feeding real audio](#feeding-real-audio).
- **Shapes:** `shape="mirror"` (the default) centers the bars, `"bars"` stands them on the baseline, and `"line"` joins the levels into one shape. A live waveform can also be a `"scope"`: raw samples traced as one line, like an oscilloscope.
- **On the timeline:** [`WaveformRegion`](#regions-and-markers) is a stretch you can move and resize, such as a loop. `WaveformMarker` is a labelled point. `WaveformHover` follows the pointer and shows the time under it.
- **Performance:** moving parts are painted outside React, and only when something changes. A waveform that is off screen or at rest uses no frames. When reduced motion is requested, live waveforms repaint a few times per second, without smoothing or idle animation.
- **Accessibility:** the seekable waveform holds a native `<input type="range">`: it takes focus, carries `aria-label`, announces the played share (or the text from `getAriaValueText`, such as a time), and supports the arrow keys, <kbd>Home</kbd>, <kbd>End</kbd>, <kbd>Page Up</kbd> and <kbd>Page Down</kbd>. Each region handle holds one too. Live waveforms are images: give them an `aria-label`.

## 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 the seekable waveform, the live waveform and the bar visualizer, is one command:

**In React**

**CLI**

The styled component, with size variants and theme styles:

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

Or the primitive alone, to style yourself:

```bash
npx shadcn@latest add @audio-ui/waveform-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 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 waveform
```

Or the parts alone, to style yourself:

```bash
npx @audio-ui/cli add waveform --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 files for every framework: `waveform.ts`, the waveform itself, with the painters of the canvas and the bars beside it (`paint-canvas.ts`, `paint-bars.ts`, and what they draw from); `frame.ts`, which runs them on animation frames; `grid.ts`, the ranges a region moves in, shared with the piano roll and the timeline; and `primitive.ts`, the little every primitive shares. Copy them into `components/audio-ui/` (`src/lib/components/audio-ui/` in Svelte).

<ItemFiles name="waveform-react" to={12} />

### 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="waveform-react" from={12} />

**Vue**

<ItemFiles name="waveform-vue" from={12} />

**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="waveform-svelte" from={12} />

**JavaScript**

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

<ItemFiles name="waveform-web" from={12} />

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

<ItemFiles name="waveform" />

**In Vue, Svelte and Web**

### 5. The styles

Optional: the waveform as the registry draws it in React, with no classes and no Tailwind. Its look is one sheet of plain CSS on the adapter's own parts, a sheet for each style (`nova`, `vega`, `maia`, `lyra`, `mira`, `luma`, `rhea`, `sera`): compose the parts as the example above does, and the sheet draws them. Only what you write yourself carries a slot of yours: `data-slot="waveform-marker-label"` on a marker's label.

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

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

By hand:

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

Both are served at `https://www.audio-ui.dev/css/`, with the skins in `/css/skins/`.

The live waveform and the bar visualizer are the same root, told apart by an attribute the sheet reads: `data-variant="live"` on a root holding a `Canvas`, or `data-variant="bars"` on a root holding `Bars` and their `Bar`s, with `data-orientation` (`horizontal` or `vertical`) and `data-align` (`start`, `center` or `end`) for where the bars grow from.

**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 waveform 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 {
  BarVisualizer,
  LiveWaveform,
  Waveform,
  WaveformHover,
  WaveformMarker,
  WaveformRegion,
  WaveformRegionHandle,
} from "@/components/audio-ui/waveform";
```

**A file, in seconds, with a playhead line and handle:**

```tsx
<Waveform
  aria-label="Track progress"
  duration={audio.duration}
  onValueChange={(seconds) => {
    audio.currentTime = seconds;
  }}
  value={currentTime}
  values={values}
  variant="playhead"
/>
```

A live waveform, scrolling with a made-up voice:

**In React**

```tsx
import { useEffect, useState } from "react";
import { LiveWaveform } from "@/components/audio-ui/waveform";
import { createSource } from "@/components/audio-ui/primitive";

/** A voice made up from a few slow waves: no microphone, no sound. */
function voiceAt(seconds: number) {
  const syllable = Math.max(0, Math.sin(seconds * 5.3)) ** 2;
  const breath = 0.55 + 0.45 * Math.sin(seconds * 0.9);
  return [Math.min(1, syllable * breath + 0.05)];
}

export function WaveformLiveDemo() {
  const [level] = useState(() => createSource<ArrayLike<number>>([0]));
  useEffect(() => {
    let frame = 0;
    const tick = (now: number) => {
      level.set(voiceAt(now / 1000));
      frame = requestAnimationFrame(tick);
    };
    frame = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(frame);
  }, [level]);
  return <LiveWaveform aria-label="Voice" mode="scrolling" source={level} />;
}
```

**A microphone, scrolling as it comes in:**

```tsx
const { level } = useAudioSignal(analyser);

<LiveWaveform aria-label="Microphone input" mode="scrolling" source={level} />;
```

**A voice, as bars:**

```tsx
const { bands } = useAudioSignal(analyser);

<BarVisualizer aria-label="Agent speaking" mirrored source={bands} />;
```

**In React**

The primitive alone, part by part:

A Root owns the position and what is shown. Everything else is a part you place in it:

- **Canvas**: draws the shape on the device pixel grid, sharp at any density, and only when something changed.
- **Bars** and **Bar**: the shape as a fixed number of elements, styled in plain CSS from `--waveform-level`.
- **Control**: the seekable surface. A press jumps to the pointer and a drag scrubs. It holds the native `<input type="range">` that takes focus and the keys, and carries the accessible name.
- **Playhead** and **Thumb**: follow the position through the `--waveform-position` CSS variable.
- **Hover**: shown at the hovered point, with the text `format` returns.
- **Marker**: a point of interest at a `value`.
- **Region** and **RegionHandle**: a named stretch laid over the waveform, moved by its body and resized by its edges.

**React**

```tsx
import { Waveform } from "@/components/audio-ui/waveform/react";

export function Player({ peaks, time, onSeek }: { peaks: number[]; time: number; onSeek: (time: number) => void }) {
  return (
    <Waveform.Root duration={120} onValueChange={onSeek} peaks={peaks} value={time}>
      <Waveform.Control aria-label="Position" className="relative h-16">
        <Waveform.Canvas className="absolute inset-0 size-full text-muted-foreground" />
        <Waveform.Playhead className="absolute inset-y-0 w-px bg-primary" />
      </Waveform.Control>
    </Waveform.Root>
  );
}
```

**Vue**

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

defineProps<{ peaks: number[]; time: number }>();
const emit = defineEmits<{ seek: [time: number] }>();
</script>

<template>
  <Waveform.Root :duration="120" :peaks="peaks" :value="time" @value-change="(next: number) => emit('seek', next)">
    <Waveform.Control aria-label="Position" class="relative h-16">
      <Waveform.Canvas class="absolute inset-0 size-full text-muted-foreground" />
      <Waveform.Playhead class="absolute inset-y-0 w-px bg-primary" />
    </Waveform.Control>
  </Waveform.Root>
</template>
```

**Svelte**

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

  let { peaks, time, onSeek }: { peaks: number[]; time: number; onSeek: (time: number) => void } = $props();
</script>

<Waveform.Root duration={120} onValueChange={onSeek} {peaks} value={time}>
  <Waveform.Control aria-label="Position" class="relative h-16">
    <Waveform.Canvas class="absolute inset-0 size-full text-muted-foreground" />
    <Waveform.Playhead class="absolute inset-y-0 w-px bg-primary" />
  </Waveform.Control>
</Waveform.Root>
```

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

**JavaScript**

```html
<audio-ui-waveform duration="120" style="display: block; position: relative">
  <audio-ui-waveform-control aria-label="Position" style="height: 4rem">
    <audio-ui-waveform-canvas style="position: absolute; inset: 0"></audio-ui-waveform-canvas>
    <audio-ui-waveform-playhead></audio-ui-waveform-playhead>
  </audio-ui-waveform-control>
</audio-ui-waveform>

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

  const waveform = document.querySelector("audio-ui-waveform");
  waveform.peaks = peaks;
  waveform.addEventListener("input", (event) => console.log(event.detail.value, event.detail.reason));
</script>
```

In the web adapter, `peaks`, `levels` and `source` are properties, not attributes, and a Hover's `format` too. The canvas, the control's input, the bars and a region's edge inputs are made for you. Each part binds a microtask after it connects: read the element's state after that.

### A live position and a live signal

Give the Root a `source`, a live position in `duration` units in the shape of an external store: `getSnapshot()` returns it and `subscribe(listener)` is called on each tick. The `--waveform-position` variable, the Canvas and the input follow it straight in the DOM, with no render. `levels` is the same for a signal, such as a microphone or an analyser: each value is a level from 0 to 1, and while it is audible the Root carries `data-active`. Any object with those two methods works, with nothing to install.

**In React**

## Feeding real audio

`values` is a plain prop: the component does not decode audio. `@/lib/engine/analysis` and the `audio-decode` lib (`npx shadcn@latest add @audio-ui/audio-decode`) turn a real audio file into `values`: `decodeAudioChannels` (from `audio-decode`) reads every channel's PCM samples at the context's sample rate, with the browser's own decoder, or for an AIFF, CAF or Apple Lossless file it refuses, as Chrome does, a decoder of its format and a resampler, loaded the first time one is needed; `computePeaks` reduces them to each slice's lowest and highest sample across all channels (so a take panned hard to one side still draws), and `normalizePeaks` scales them so the loudest sample reaches full height.

```tsx
import { computePeaks, normalizePeaks } from "@/lib/engine/analysis";
import { decodeAudioChannels } from "@/lib/engine/files";

const context = new AudioContext();
const channels = await decodeAudioChannels(context, await file.arrayBuffer());

const values = normalizePeaks(computePeaks(channels, 4096));
```

The second argument to `computePeaks` is a resolution, not a bar count: the canvas fits whatever you pass to its own width and to any `range`. Compute it once per file, with more slices than the widest view you expect will show (a few thousand covers a zoomed-in clip editor). For a simpler shape, `downsampleWaveform` and `normalizeWaveform` give one amplitude per slice instead.

**In React**

## Showing part of the audio

`range` is the stretch of the audio to show, `[start, end]` in `duration` units. Everything follows it: the bars are drawn from that stretch of `values` alone, a press seeks inside it, the input's keys stay inside it, and regions and markers are placed across it.

```tsx
<Waveform
  aria-label="Clip"
  duration={source.duration}
  range={[clip.offset, clip.offset + clip.length]}
  values={source.peaks}
/>
```

When the position is outside the stretch, the root carries `data-outside` and the playhead is hidden, rather than pinned to an edge it hasn't reached. Past the largest canvas a browser will draw (16,384 pixels a side), the bitmap is drawn coarser rather than going blank.

**In React**

## Following playback

`value` re-renders React each time it changes, which is fine for a `timeupdate` event a few times a second. For a playhead that glides every animation frame, pass a `source`, an object in the shape of an external store:

```ts
interface WaveformSource {
  getSnapshot: () => number; // the position, in `duration` units
  subscribe: (listener: () => void) => () => void;
}
```

The waveform subscribes to it and moves the playhead, repaints the canvas and updates the input itself. While the pointer scrubs, the waveform follows the pointer and ignores the source until release; the same holds for a controlled `value` that updates late.

**In React**

## Regions and markers

Anything inside `Waveform` is laid over the canvas, on the same timeline. A region is `[start, end]` in `duration` units; drag its body to move it, and give it a handle per edge to resize it:

```tsx
const [loop, setLoop] = useState<readonly [number, number]>([48, 96]);

<Waveform aria-label="Track progress" duration={180} values={values}>
  <WaveformRegion onValueChange={setLoop} value={loop}>
    <WaveformRegionHandle aria-label="Loop start" edge="start" />
    <WaveformRegionHandle aria-label="Loop end" edge="end" />
  </WaveformRegion>
  <WaveformMarker value={124}>Chorus</WaveformMarker>
  <WaveformHover format={formatTime} />
</Waveform>
```

A press on a region never seeks the waveform underneath. Each handle is a slider of its own: it takes focus, and the arrow keys, <kbd>Page Up</kbd> / <kbd>Page Down</kbd>, <kbd>Home</kbd> and <kbd>End</kbd> move its edge, which stops `minLength` short of the other one. Leave the handles out for a region that only moves, or pass `movable={false}` for one that only resizes.

**In React**

## Live signals

A live waveform reads from a `source`, an object in the shape of an external store whose snapshot is the current levels, `0–1` each:

```ts
interface LevelsSource {
  getSnapshot: () => ArrayLike<number>;
  subscribe: (listener: () => void) => () => void;
}
```

The `use-audio-signal` hook (`npx shadcn@latest add @audio-ui/use-audio-signal`) reads two of them from an `AnalyserNode`, every animation frame and only while something is drawing them:

```tsx
const { level, bands, samples } = useAudioSignal(analyser, { bandCount: 32 });
```

- `level` is the loudest sample of the moment, as a single level. Draw it with `mode="scrolling"`: the waveform records it over time, the newest entering from the right, or from the middle outwards with `mirrored`. When the signal stops (pass `null` as the analyser to pause), the trace holds still.
- `bands` is the spectrum as log-spaced frequency bands, low to high. Draw it with a `BarVisualizer`, or a `LiveWaveform` in its default `mode="static"`: the bars stay in place and follow the bands, rising at once and falling smoothly.
- `samples` is the raw waveform of the moment, `-1` to `1`. Draw it with `shape="scope"`.

Any signal works. A source is an object with `getSnapshot()` and `subscribe(listener)`, which you push to yourself, from a WebSocket, a worklet or a test:

```tsx
let frame = new Float32Array(16);
const listeners = new Set<() => void>();

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

socket.onmessage = (event) => {
  frame = event.data;
  for (const listener of listeners) listener();
};
```

While its signal is audible, a live waveform carries `data-active`. `idle` picks what the bars do meanwhile (`"pulse"` breathes, `"wave"` ripples), and `loading` sweeps across them while a connection is on its way.

**In React**

## Theming

Colors come from CSS, and the canvas repaints when the theme changes:

**CSS variables**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `--waveform-color` |  | `text color` | Bars ahead of the position, and every bar of a live waveform. |
| `--waveform-progress-color` |  | `--waveform-color` | Bars behind the position. |
| `--waveform-bar-radius` |  | `0px` | Bar corner radius on the canvas (any CSS length). |
| `--waveform-position` |  |  | Set on the root: the playback position, as a percentage. |
| `--waveform-level` |  |  | Set on each bar of a `BarVisualizer`: its level, `0–1`. |

The bars of a `BarVisualizer` are plain elements: restyle them with `.cn-bar-visualizer-bar`. Those the playback position has passed carry `data-played`.

## Interaction

**Control**

- A press seeks, a drag scrubs, and the end of the gesture commits.
- Shift with a drag selects a stretch instead, reported to `onSelectionChange` and `onSelectionCommitted`. Without them a Shift drag is an ordinary seek.
- The arrows move by `step`, Shift with an arrow and Page Up and Page Down by `largeStep`, Home and End go to the ends.
- Nothing seeks while `disabled` or `loading`.

**Regions**

- Dragging a Region's body moves it, unless `movable` is false. Dragging a RegionHandle resizes that edge.
- On a handle's input, the arrows and Page keys move the edge and Home and End send it to its limit.
- A press on a region never reaches the Control underneath.

## API reference

**In React**

### Registry component

`aria-label`, `aria-labelledby`, and `aria-describedby` are forwarded to the element that needs them: the waveform's input, a region handle's input, or the live waveform itself.

#### Waveform

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `values` | `ArrayLike<number> \| { min, max }` |  | The audio's shape at any resolution: `0–1` amplitudes, or each slice's lowest and highest sample, `-1–1`. |
| `range` | `readonly [number, number]` | `whole audio` | The stretch of the audio to show, `[start, end]` in `duration` units: a clip's window onto its source, a zoomed view. The playhead, seeking, hover, regions and markers all follow it. Defaults to the whole audio. While the position is outside it, the root carries `data-outside`. |
| `value` | `number` |  | Controlled position, from `0` to `duration`. |
| `defaultValue` | `number` | `0` | Uncontrolled starting position. |
| `source` | `WaveformSource` |  | A live position followed outside React; takes precedence over `value`. |
| `duration` | `number` | `1` | Length of the audio, in the unit `value` is in (typically seconds). |
| `step` | `number` | `duration / 100` | Step for the arrow keys. Defaults to a hundredth of `duration`. |
| `largeStep` | `number` | `duration / 10` | Step for Page Up/Page Down and Shift + arrow keys. Defaults to a tenth of `duration`. |
| `disabled` | `boolean` | `false` | Disables pointer and keyboard interaction. |
| `loading` | `boolean` | `false` | Whether the audio is still on its way. Seeking waits, and the bars sweep. |
| `onValueChange` | `(value: number, eventDetails) => void` |  | Fires while seeking. `eventDetails.reason` is `"press"`, `"drag"`, `"keyboard"`, or `"input-change"`; call `eventDetails.cancel()` to reject it. |
| `onValueCommitted` | `(value: number, eventDetails) => void` |  | Fires when a seek that moved the position ends. |
| `getAriaValueText` | `(value: number, duration: number) => string` | `played share` | Returns how the position is announced, e.g. `"0:12 of 1:42"`. Defaults to the played share, e.g. `"30%"`. |
| `onSelectionChange` | `(range: readonly [number, number], eventDetails) => void` |  | Fires while a stretch is selected by dragging with Shift held, as `[start, end]` in `duration` units; feed it to a `Waveform.Region`. A plain press and drag still seek. `eventDetails.cancel()` keeps the selection as it was. |
| `onSelectionCommitted` | `(range: readonly [number, number], eventDetails) => void` |  | Fires when a selection that changed ends. |
| `shape` | `"mirror" \| "bars" \| "line"` | `"mirror"` | How the amplitudes are drawn. |
| `barWidth` | `number` | `2` | Bar width, in CSS pixels, snapped to whole device pixels. |
| `barGap` | `number` | `1` | Space between bars, in CSS pixels, snapped to whole device pixels. |
| `variant` | `"default" \| "playhead"` | `"default"` | `playhead` adds a playhead line and a handle. |
| `className` | `string` |  | Classes for the waveform surface. |

#### WaveformRegion

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `readonly [number, number]` |  | Controlled region, as `[start, end]` in `duration` units. |
| `defaultValue` | `readonly [number, number]` | `whole timeline` | Uncontrolled starting region. |
| `minLength` | `number` | `the waveform's step` | The shortest the region can be resized to, in `duration` units. Defaults to the root's `step`. |
| `movable` | `boolean` | `true` | Whether dragging the region's body moves it. |
| `disabled` | `boolean` | `false` | Also disabled when the waveform is. |
| `onValueChange` | `(value, eventDetails) => void` |  | Fires while moving or resizing. `eventDetails.edge` is `"start"`, `"end"` or `"both"`; `eventDetails.reason` is `"drag"`, `"keyboard"` or `"input-change"`. |
| `onValueCommitted` | `(value, eventDetails) => void` |  | Fires when a move or resize that changed the region ends. |

`WaveformRegionHandle` takes `edge` (`"start"` or `"end"`) and `getAriaValueText`. `WaveformMarker` takes `value` and shows its children as a label. `WaveformHover` takes `format`, which prints the hovered position; without it only the line shows.

#### LiveWaveform

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `source` | `LevelsSource \| null` |  | A live position followed outside React; takes precedence over `value`. |
| `mode` | `"static" \| "scrolling"` | `"static"` | `static` spreads the current levels across the width; `scrolling` records the loudest one over time. |
| `scrollSpeed` | `number` | `60` | How fast the scrolling mode moves, in CSS pixels per second. |
| `shape` | `"mirror" \| "bars" \| "line" \| "scope"` | `"mirror"` | How the signal is drawn. `scope` traces raw samples instead of levels. |
| `gain` | `number` | `1` | Visual gain applied to the levels before they are drawn. |
| `mirrored` | `boolean` | `false` | Makes the drawing symmetric: the first level in the center, or, when scrolling, the newest one, with older ones moving out on both sides. |
| `idle` | `"none" \| "pulse" \| "wave"` | `"none"` | In `static` mode, what the bars do while there is no signal. |
| `loading` | `boolean` | `false` | Whether the audio is still on its way. Seeking waits, and the bars sweep. |

#### BarVisualizer

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `source` | `LevelsSource \| null` |  | A live position followed outside React; takes precedence over `value`. |
| `count` | `number` | `24` | How many bars to draw. The levels are fitted to them. |
| `mirrored` | `boolean` | `false` | Mirrors the levels around the middle bar, the lowest band in the center. |
| `minLevel` | `number` | `0.08` | Resting level, 0…1: silent bars keep this much of their size. |
| `gain` | `number` | `1` | Visual gain applied to the levels before they are drawn. |
| `idle` | `"none" \| "pulse" \| "wave"` | `"none"` | What the bars do while there is no signal. |
| `loading` | `boolean` | `false` | Whether the audio is still on its way. Seeking waits, and the bars sweep. |
| `align` | `"start" \| "center" \| "end"` | `"center"` | Where the bars grow from. |
| `orientation` | `"horizontal" \| "vertical"` | `"horizontal"` | `vertical` stacks the bars and grows them sideways. |

The `Waveform` primitive that installs with it exposes the parts these components are built from:

**Parts**

| Name | Description |
| --- | --- |
| `Waveform.Root` | Owns the data (`peaks`, or a live `levels` source) and the position (`value`, `source`, `duration`). Carries `data-active` while a live signal is audible. |
| `Waveform.Control` | The seekable surface; holds the input. Leave it out for a waveform that is only shown. |
| `Waveform.Canvas` | Draws on a canvas: `variant`, `mode`, `scrollSpeed`, `barWidth`, `barGap`, `barRadius`, `minBarHeight`, `lineWidth`, `gain`, `mirrored`, `idle`. |
| `Waveform.Bars, Waveform.Bar` | Draws as elements: `count`, `minLevel`, `gain`, `mirrored`, `idle`. Each bar gets `--waveform-level`, `data-index` and `data-played`. |
| `Waveform.Region, Waveform.RegionHandle` | A stretch of the timeline, named by `region`, and the handle of one of its edges. What they report goes to the Root's `onRegionChange` and `onRegionCommitted`, with the region's name in the details. |
| `Waveform.Marker` | A point on the timeline. |
| `Waveform.Playhead, Waveform.Thumb` | Follow the playback position. |
| `Waveform.Hover` | Shown at the hovered position; its `format` turns that position into the text it writes. |

Every part accepts a `render` prop and `className` / `style` as functions of state, and exposes that state as data attributes such as `data-disabled`, `data-dragging` and `data-loading`.

### Options

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

| Option | Type | Default | |
| --- | --- | --- | --- |
| `value`, `defaultValue` | `number` | `0` | The position, controlled or starting. |
| `source` | `{ getSnapshot, subscribe }` | | A live position, followed with no render. It takes precedence over `value`. |
| `duration` | `number` | `1` | The length of the audio, in the unit `value` is in. |
| `peaks` | `number[]` or `{ min, max }[]` | | The shape, at any resolution: a level per slice, or the lowest and highest sample of each. |
| `levels` | `{ getSnapshot, subscribe }` | | A live signal drawn instead of `peaks`. |
| `range` | `[start, end]` | the whole audio | The stretch shown. The position, seeking, hover, regions and markers follow it. |
| `step`, `largeStep` | `number` | a hundredth, a tenth of `duration` | The keys' steps. |
| `loading` | `boolean` | `false` | The audio is still on its way. Seeking waits. |
| `disabled` | `boolean` | `false` | Takes no gesture. |
| `name` | `string` | | The form field's name, carried by the seek input. |
| `onValueChange`, `onValueCommitted` | `(value, details) => void` | | A seek, and its end. |
| `onSelectionChange`, `onSelectionCommitted` | `(range, details) => void` | | A Shift drag. |
| `onRegionChange`, `onRegionCommitted` | `(region, details) => void` | | A region moved or resized, with `details.region` and `details.edge`. |

A Region takes `region` (its name), `value` or `defaultValue` (`[start, end]`), `minLength`, `movable` and `disabled`; a RegionHandle takes `edge` and the same `region`. The Canvas takes `variant`, `mode`, `barWidth`, `barGap`, `barRadius`, `gain`, `idle` and the rest of the painter's options, the Bars `count`, `gain`, `idle`, `minLevel` and `mirrored`. Colors come from `--waveform-color` and `--waveform-progress-color`.

### What a change reports

`details` carries:

- `reason`: `"press"`, `"drag"`, `"keyboard"` or `"input-change"`.
- `source`: `"mouse"`, `"touch"`, `"pen"`, `"keyboard"`, `"programmatic"` or `"agent"`.
- `event` and `cancel()`: the DOM event behind it, and the refusal.
- For a region, `region` (its name) and `edge` (`"start"`, `"end"` or `"both"`).

In the web adapter, the seek is the `input` and `change` events, and the selection and the regions are `selectionchange`, `selectioncommit`, `regionchange` and `regioncommit`, each with a `detail` of the value and its reasons. `event.preventDefault()` refuses a change.

### States to style from

- `data-dragging` while a pointer scrubs or selects, `data-loading`, `data-disabled` on every part.
- `data-active` on the Root while a live signal is audible, and `data-outside` while the position is outside the stretch shown.
- `data-played` on the bars the position has passed, `data-index` on a bar, `data-region` and `data-edge` on a region and its handles.

### Parts

**In React, Vue and Svelte**

| Part | Element | Props |
| --- | --- | --- |
| `Waveform.Bar` | `span` | `index: key` |
| `Waveform.Bars` | `div` | `count: number`, `gain: number`, `idle: string`, `minLevel: number`, `mirrored: boolean` |
| `Waveform.Canvas` | `canvas` | `barGap: number`, `barRadius: number`, `barWidth: number`, `gain: number`, `idle: string`, `lineWidth: number`, `minBarHeight: number`, `mirrored: boolean`, `mode: string`, `scrollSpeed: number`, `variant: string` |
| `Waveform.Control` | `div` |  |
| `Waveform.Hover` | `div` | `format: value` |
| `Waveform.Marker` | `div` | `value: number` |
| `Waveform.Playhead` | `div` |  |
| `Waveform.Region` | `div` | `defaultValue: value`, `disabled: boolean`, `minLength: number`, `movable: boolean`, `region: key`, `value: value` |
| `Waveform.RegionHandle` | composed of other parts |  |
| `Waveform.Root` | `div` |  |
| `Waveform.Thumb` | `div` |  |

**In Web**

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

`audio-ui-waveform`, `audio-ui-waveform-bar`, `audio-ui-waveform-bars`, `audio-ui-waveform-canvas`, `audio-ui-waveform-control`, `audio-ui-waveform-hover`, `audio-ui-waveform-input`, `audio-ui-waveform-marker`, `audio-ui-waveform-playhead`, `audio-ui-waveform-region`, `audio-ui-waveform-region-end`, `audio-ui-waveform-region-end-input`, `audio-ui-waveform-region-start`, `audio-ui-waveform-region-start-input`, `audio-ui-waveform-thumb`

### Events

| React and Svelte | Vue | Web |
| --- | --- | --- |
| `onRegionChange` | `@region-change` | `regionchange` |
| `onRegionCommitted` | `@region-committed` | `regioncommit` |
| `onSelectionChange` | `@selection-change` | `selectionchange` |
| `onSelectionCommitted` | `@selection-committed` | `selectioncommit` |
| `onValueChange` | `@value-change` | `input` |
| `onValueCommitted` | `@value-committed` | `change` |
