# Agent Skill > Give your coding agent the audio/ui skill so it picks the right component, wires it to Web Audio without clicks, keeps live data out of React and styles the primitives. The audio/ui skill gives a coding agent the library's rules: which layer and component fit a task, how to install them, how to wire them to the Web Audio API, how to feed meters and playheads without re-rendering React, how to style the headless primitives, and how to let an AI model drive them. ## Install the skill Works with Claude Code, Cursor, Codex and any agent that supports the open skills format. ```bash npx skills add ouestlabs/audio-ui ``` ### In Claude Code, as a plugin The repository is also a Claude Code plugin marketplace, so Claude Code installs and updates the skills itself: ```text /plugin marketplace add ouestlabs/audio-ui /plugin install audio-ui@audio-ui ``` On Claude Code 2.1.275 or later, one line does both: `/plugin install audio-ui --marketplace ouestlabs/audio-ui`. The plugin holds four skills and no hook, command or server, and it follows the repository: `/plugin marketplace update audio-ui` brings the latest rules. The agent loads each skill on its own when a task needs it, so a Vue knob does not pay for the design skins. Their rules come with incorrect and correct code for each case: | Skill | Rules | What they cover | | --- | --- | --- | | `audio-ui` | Values and events, accessibility, styling, AI control | Picking and installing components, controlled values, change versus commit, accessible names, registry props and tokens, typed tools a model calls to compose, edit and mix | | `web-audio` | Web Audio, live data | Starting the audio context, ramping parameters, dB to gain, scheduling on the audio clock, meters, spectra, waveforms and playheads fed by a source, without a render per frame | | `design` | Design | Retro, minimal and modern skins for the headless primitives, and composing a look from a brief | | `core` | Without React | Building the controls for Vue, Svelte, web components or the plain DOM on the framework-free controllers of `@audio-ui/core` | The skills live in the [audio-ui repository](https://github.com/ouestlabs/audio-ui/tree/main/skills), and CI checks that every name they mention exists in the library. To install them by hand, copy the folders of `skills/` into your agent's skills directory (for Claude Code, `.claude/skills/`). ## What it does Once installed, the agent uses it whenever you ask for a knob, fader, XY pad, meter, waveform, timeline, sequencer, piano roll or any synth, mixer or DAW interface in React. It will: 1. Read your project to see if it uses shadcn/ui, plain React or another framework, then choose the registry, `@audio-ui/react` or `@audio-ui/core`. 2. Find the right component and read its docs before writing code. 3. Install it with your package manager. 4. Connect the control to your audio code the safe way, without clicks while dragging, and feed live displays without re-rendering React. 5. Check keyboard access and accessible names. ## Add the MCP server The skill works best next to the [MCP server](/docs/mcp), which lets the agent look up components and docs live instead of relying on memory. ## Example prompts - Build a synth control panel with Knob, XY Pad and Fader. - Add an equalizer with a Plot and draggable band handles. - Make a piano roll with a keyboard, a velocity lane and a loop range. - Show the live level of my microphone on a stereo meter. - Style a knob with my own CSS, without Tailwind. - Let the chat write a bassline into the piano roll. --- # REST API > Read the components, their docs and the catalog as JSON from https://www.audio-ui.dev/api/v1: public, read-only and versioned. The REST API gives programs and agents what the docs say, as JSON: the components, their docs as markdown, a search of the docs and the catalog of ready-made blocks. It answers the same questions as the [MCP server](/docs/mcp), for any client that speaks HTTP. ``` https://www.audio-ui.dev/api/v1 ``` It is public and read-only: no key, no account. Answers can be read from any origin and are cached for five minutes. The whole API is described in OpenAPI 3.1 at [/openapi.json](/openapi.json), and listed at [/.well-known/api-catalog](/.well-known/api-catalog). ## Endpoints **Endpoints** | Name | Description | | --- | --- | | `GET /api/v1` | The entry point: the version and where every endpoint is. | | `GET /api/v1/components` | Every component. `kind` keeps one kind: `elements`, `workstation` or `devices`. | | `GET /api/v1/components/{name}` | One component and its docs as markdown. `section` returns one part, such as `installation` or `api-reference`. | | `GET /api/v1/search` | The parts of the docs that answer `q`, best first, `limit` of them (8 by default, 20 at most). | | `GET /api/v1/catalog` | The ready-made blocks and demos, 25 at a time. `q` searches them, `offset` turns the page. | Find a component, then read the part of its docs you need: ```bash curl "https://www.audio-ui.dev/api/v1/search?q=log+scale+knob" curl "https://www.audio-ui.dev/api/v1/components/knob?section=api-reference" ``` Every component carries the command that installs it, such as `npx shadcn@latest add @audio-ui/knob`. ## Errors Every error is JSON, whatever the request accepts, with the status, a stable code, what went wrong and what to do next: ```json { "error": "not_found", "message": "There is no component named \"knobb\".", "hint": "Did you mean knob? List the components at https://www.audio-ui.dev/api/v1/components, or search them at https://www.audio-ui.dev/api/v1/search?q=.", "status": 404 } ``` **Error codes** | Name | Description | | --- | --- | | `invalid_parameter` | 400: a query parameter is missing or out of range. The message names it. | | `not_found` | 404: no component of that name, or no endpoint at that address. | | `method_not_allowed` | 405: the API only reads. Send a GET or a HEAD. | | `rate_limited` | 429: too many requests from one address. Wait for `Retry-After`. | ## Rate limits Each address may send 120 requests a minute, counted in each Cloudflare location. Every answer states the quota in a `RateLimit-Policy` header, from the IETF [RateLimit header fields](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/): ``` RateLimit-Policy: "api";q=120;w=60 ``` Past it, the API answers 429 with a `RateLimit` header that says nothing is left in the window, and a `Retry-After` header in seconds. Wait that long, then go on at a slower pace: ``` HTTP/1.1 429 Too Many Requests RateLimit: "api";r=0;t=60 Retry-After: 60 ``` ## Versioning and deprecation The version is in the path: `/api/v1`. Within a version, changes only add: new endpoints, new optional parameters, new fields in the answers. Ignore the fields you do not know. A change that could break a client, such as removing or renaming an endpoint, a parameter or a field, ships as a new version, `/api/v2`, and `/api/v1` keeps answering beside it. An endpoint is deprecated at least six months before it is removed. From that day: - Its answers carry a `Deprecation` header ([RFC 9745](https://www.rfc-editor.org/rfc/rfc9745)) with the date it was deprecated, and a `Sunset` header ([RFC 8594](https://www.rfc-editor.org/rfc/rfc8594)) with the date after which it may stop answering. - Its entry in [/openapi.json](/openapi.json) is marked `deprecated`. - This page says what replaces it. Nothing is deprecated today. [/api](/api) lists the versions and their status. The registry, the markdown docs, [llms.txt](/llms.txt) and the MCP server are not part of this API: they follow their own formats, the shadcn registry schema, llmstxt.org and the MCP protocol version. --- # Devices > What a device is, the four pieces it comes in, and what every device shares: the sidechain, the tempo, the latency and the tools an agent drives it with. The catalog is grouped as in a mixer: dynamics, EQ and filters, distortion, delay and reverb, modulation, utility and instruments. A device is an effect or an instrument that you can plug in, not a widget with audio inside. It comes in four pieces that share one description, so you take the ones you need: a host that has its own audio engine keeps the state and the panel, an agent keeps the state and the tools, and a page that only wants sound takes them all. | Piece | What it is | Installs as | | --- | --- | --- | | **State** | The parameters and their ranges, as a plain object | `device` | | **Panel** | Draws a state and sends the new one back. It makes no sound | `panel` | | **Engine** | Plays a state with Web Audio nodes | `engine` | | **Tools** | What an agent calls to change the state | `deviceTools` | `npx shadcn@latest add @audio-ui/compressor` installs a device's state, engine and panel in `components/audio-ui/devices/compressor/`. Each piece also installs on its own (`@audio-ui/compressor-device`, `-engine`, `-panel`), so a host with its own engine takes only the state and the panel. The tools come from `@audio-ui/core/device`. Every device page has a block that wires the pieces to a loop: `@audio-ui/block-compressor`. To put several in a row, in the order the sound goes through them, use the [Device chain](/docs/components/base/device-chain). ## One description A device is its parameters. Write them once, with their ranges and units, and the panel, the state and the tool an agent drives it with all come from that description. A call a model could send, with a number out of range or a word where a number goes, never throws: the value is brought into range, a parameter that is not one is refused by name, and the panel follows. The code of a device is under [Your own device](#your-own-device). ## Catalog ### Dynamics | Device | Use it to | | --- | --- | | [Compressor](/docs/components/base/compressor) | Bring loud parts down, or duck one signal with another. | | [Multiband compressor](/docs/components/base/multiband) | Compress the lows, mids and highs apart. | | [Limiter](/docs/components/base/limiter) | Keep the sound under a ceiling. | | [Gate](/docs/components/base/gate) | Cut the sound between hits. | | [De-esser](/docs/components/base/deesser) | Soften the sharp s and t of a voice. | | [Transient shaper](/docs/components/base/transient) | Add or take away the attack and the sustain of a hit. | ### Tone | Device | Use it to | | --- | --- | | [Equalizer](/docs/components/base/equalizer) | Shape the spectrum with four bands. | | [Channel EQ](/docs/components/base/channel-eq) | Do the quick tone job of a mixer strip. | | [Filter](/docs/components/base/filter) | Cut or isolate part of the spectrum. | ### Distortion | Device | Use it to | | --- | --- | | [Overdrive](/docs/components/base/overdrive) | Push only the mids into a soft clip, as a pedal does. | | [Saturator](/docs/components/base/saturator) | Add warmth or dirt with one of four curves. | | [Distortion](/docs/components/base/distortion) | Round off the peaks of the whole signal. | | [Redux](/docs/components/base/redux) | Roughen the sound by cutting its bits and its sample rate. | ### Space and modulation | Device | Use it to | | --- | --- | | [Delay](/docs/components/base/delay) | Repeat the sound, free or in time with the tempo. | | [Reverb](/docs/components/base/reverb) | Put the sound in a room. | | [Chorus](/docs/components/base/chorus) | Thicken the sound with a swept delay. | | [Phaser](/docs/components/base/phaser) | Sweep notches through the sound, or flange it. | | [Auto pan](/docs/components/base/auto-pan) | Move the sound between the speakers, or its level up and down. | ### Utility and instruments | Device | Use it to | | --- | --- | | [Utility](/docs/components/base/utility) | Set the gain, the pan and the width, switch to mono or flip the phase. | | [Mid/side](/docs/components/base/mid-side) | Set the centre and the sides apart, and keep the bass in the middle. | | [Pocket synth](/docs/components/base/pocket-synth) | Play one oscillator through a resonant filter. | | [Wave shaper](/docs/components/base/wave-shaper) | Play two detuned oscillators through a distortion and a filter. | ## The state A state is a plain object keyed by parameter id. It holds numbers, booleans and strings, and it is safe to turn into JSON. The device keeps no instance, so you store the state, save it with your project and send it where you like. ```ts import { compressorDevice } from "@/components/audio-ui/devices/compressor/device"; const state = compressorDevice.defaults(); // { enabled: true, thresholdDb: -18, ratio: 4, attackMs: 5, ... } compressorDevice.set(state, "thresholdDb", -200); // a new state, brought to -60 compressorDevice.sanitize(JSON.parse(saved)); // a loaded project, repaired ``` A parameter is a number with a range, a switch or a choice from a list. The id of the device, `audioui.compressor`, is what a project stores. It is not the panel, which you can restyle without breaking anyone's session. ## The panel A panel is controlled. It keeps no state: it draws the one it is given and returns the whole new state. ```tsx import { CompressorPanel } from "@/components/audio-ui/devices/compressor/panel"; ; ``` Most panels draw something the state means, such as a transfer curve, a frequency response or a set of echoes, with a handle you drag, over the knobs. The knobs come from the descriptors of the device, with their ranges, steps and readouts. ## One device, several skins The panel is a view over the descriptors of the device, so a skin changes how it looks and nothing else: the same state, the same engine, the same values. The compressor, drawn with the Nova style: ```tsx "use client"; import { createSource } from "@audio-ui/react"; import { useEffect, useRef, useState } from "react"; import { CompressorPanel } from "@/components/audio-ui/devices/compressor/panel"; import { useDemoSource } from "@/hooks/use-demo-source"; import { useMasterBus } from "@/hooks/use-master-bus"; import { usePlaySwitch } from "@/hooks/use-play-switch"; import { type CompressorState, compressorDevice, } from "@/components/audio-ui/devices/compressor/device"; import { type CompressorEngine, createCompressorEngine, } from "@/components/audio-ui/devices/compressor/engine"; import { demoKey, renderDemoSource, } from "@/lib/demo-sound"; import { webAudio } from "@/lib/web-audio"; const FLOOR_DB = -80; const FFT_SIZE = 1024; /** How fast the level falls back between pulses, in dB per frame. */ const LEVEL_FALL_DB = 1.2; const MASTER_VOLUME = 0.7; /** * A compressor you can plug in: its state, a panel that draws it, an engine * that plays it, side by side. Each is its own file and none knows the others: * the state is a plain object, so a host keeps its own and uses what it needs. * Play it from its session and turn the knobs; switch Sidechain on and a kick ducks a held chord. */ export function BlockCompressor() { const [state, setState] = useState(() => compressorDevice.defaults() ); const { playing } = usePlaySwitch(); const master = useMasterBus(MASTER_VOLUME); const [level] = useState(() => createSource(FLOOR_DB)); const engine = useRef(null); const stateRef = useRef(state); stateRef.current = state; // With the key on, a held chord is ducked by the kick of a loop: the key is heard by the compressor only. const keyed = state.external; const name = useDemoSource(keyed ? "chord" : "groove"); useEffect(() => { const ctx = webAudio.getContext(); if (!(playing && ctx && master)) { return; } ctx.resume(); let cancelled = false; let stop = () => undefined; const buffers = Promise.all([ renderDemoSource(name, ctx.sampleRate), keyed ? renderDemoSource(demoKey(name), ctx.sampleRate) : null, ]); buffers.then(([signal, key]) => { if (cancelled) { return; } const source = ctx.createBufferSource(); source.buffer = signal; source.loop = true; const keySource = key ? ctx.createBufferSource() : null; const compressor = createCompressorEngine(ctx, stateRef.current); const tap = ctx.createAnalyser(); tap.fftSize = FFT_SIZE; source.connect(tap); source.connect(compressor.input); if (keySource && key) { keySource.buffer = key; keySource.loop = true; keySource.connect(compressor.sidechain); } compressor.output.connect(master); engine.current = compressor; const startAt = ctx.currentTime + 0.05; source.start(startAt); keySource?.start(startAt); const samples = new Float32Array(new ArrayBuffer(tap.fftSize * 4)); let held = FLOOR_DB; let frame = 0; const tick = () => { tap.getFloatTimeDomainData(samples); let peak = 0; for (const sample of samples) { peak = Math.max(peak, Math.abs(sample)); } const db = peak > 0 ? Math.max(FLOOR_DB, 20 * Math.log10(peak)) : FLOOR_DB; held = Math.max(db, held - LEVEL_FALL_DB); level.set(held); frame = requestAnimationFrame(tick); }; frame = requestAnimationFrame(tick); stop = () => { cancelAnimationFrame(frame); source.stop(); source.disconnect(); keySource?.stop(); keySource?.disconnect(); tap.disconnect(); compressor.dispose(); engine.current = null; level.set(FLOOR_DB); }; }); return () => { cancelled = true; stop(); }; }, [keyed, level, master, name, playing]); // The engine follows the state, whoever changed it: a knob or a call. useEffect(() => { engine.current?.update(state); }, [state]); return (
); } ``` and with the Vega style, from the same device and the same panel: ```tsx "use client"; import { createSource } from "@audio-ui/react"; import { useEffect, useRef, useState } from "react"; import { CompressorPanel } from "@/components/audio-ui/devices/compressor/panel"; import { useDemoSource } from "@/hooks/use-demo-source"; import { useMasterBus } from "@/hooks/use-master-bus"; import { usePlaySwitch } from "@/hooks/use-play-switch"; import { type CompressorState, compressorDevice, } from "@/components/audio-ui/devices/compressor/device"; import { type CompressorEngine, createCompressorEngine, } from "@/components/audio-ui/devices/compressor/engine"; import { demoKey, renderDemoSource, } from "@/lib/demo-sound"; import { webAudio } from "@/lib/web-audio"; const FLOOR_DB = -80; const FFT_SIZE = 1024; /** How fast the level falls back between pulses, in dB per frame. */ const LEVEL_FALL_DB = 1.2; const MASTER_VOLUME = 0.7; /** * A compressor you can plug in: its state, a panel that draws it, an engine * that plays it, side by side. Each is its own file and none knows the others: * the state is a plain object, so a host keeps its own and uses what it needs. * Play it from its session and turn the knobs; switch Sidechain on and a kick ducks a held chord. */ export function BlockCompressor() { const [state, setState] = useState(() => compressorDevice.defaults() ); const { playing } = usePlaySwitch(); const master = useMasterBus(MASTER_VOLUME); const [level] = useState(() => createSource(FLOOR_DB)); const engine = useRef(null); const stateRef = useRef(state); stateRef.current = state; // With the key on, a held chord is ducked by the kick of a loop: the key is heard by the compressor only. const keyed = state.external; const name = useDemoSource(keyed ? "chord" : "groove"); useEffect(() => { const ctx = webAudio.getContext(); if (!(playing && ctx && master)) { return; } ctx.resume(); let cancelled = false; let stop = () => undefined; const buffers = Promise.all([ renderDemoSource(name, ctx.sampleRate), keyed ? renderDemoSource(demoKey(name), ctx.sampleRate) : null, ]); buffers.then(([signal, key]) => { if (cancelled) { return; } const source = ctx.createBufferSource(); source.buffer = signal; source.loop = true; const keySource = key ? ctx.createBufferSource() : null; const compressor = createCompressorEngine(ctx, stateRef.current); const tap = ctx.createAnalyser(); tap.fftSize = FFT_SIZE; source.connect(tap); source.connect(compressor.input); if (keySource && key) { keySource.buffer = key; keySource.loop = true; keySource.connect(compressor.sidechain); } compressor.output.connect(master); engine.current = compressor; const startAt = ctx.currentTime + 0.05; source.start(startAt); keySource?.start(startAt); const samples = new Float32Array(new ArrayBuffer(tap.fftSize * 4)); let held = FLOOR_DB; let frame = 0; const tick = () => { tap.getFloatTimeDomainData(samples); let peak = 0; for (const sample of samples) { peak = Math.max(peak, Math.abs(sample)); } const db = peak > 0 ? Math.max(FLOOR_DB, 20 * Math.log10(peak)) : FLOOR_DB; held = Math.max(db, held - LEVEL_FALL_DB); level.set(held); frame = requestAnimationFrame(tick); }; frame = requestAnimationFrame(tick); stop = () => { cancelAnimationFrame(frame); source.stop(); source.disconnect(); keySource?.stop(); keySource?.disconnect(); tap.disconnect(); compressor.dispose(); engine.current = null; level.set(FLOOR_DB); }; }); return () => { cancelled = true; stop(); }; }, [keyed, level, master, name, playing]); // The engine follows the state, whoever changed it: a knob or a call. useEffect(() => { engine.current?.update(state); }, [state]); return (
); } ``` ## The engine ```ts import { createCompressorEngine } from "@/components/audio-ui/devices/compressor/engine"; const engine = createCompressorEngine(ctx, state); source.connect(engine.input); engine.output.connect(ctx.destination); engine.update(nextState); // parameters ramp: no click engine.dispose(); ``` An engine is a function of an audio context and a state. It gives you an `input`, an `output`, an `update` and a `dispose`, and it moves every parameter with a ramp so that turning a knob never clicks. The numbers that go on the nodes come from a pure function of the state, such as `compressorSettings(state)`, that you can read and test without an audio context. Some engines add to this: | Member | On | What it is | | --- | --- | --- | | `sidechain` | Compressor, gate | The input of the signal that drives the device. | | `ready` | Every device that runs a worklet | A promise that resolves once the detector can be in the graph. The compressor makes its detector the first time its key is on. | | `reduction` | Compressor, limiter, de-esser | The gain being taken off, in dB. Read it each frame. | | `noteOn`, `noteOff` | Instruments | Start and release a note. | A worklet is loaded from a blob, so there is no file to serve. Until `ready` resolves, a device that needs one passes the signal unchanged. In a context with no worklets it never resolves to `true`. ## Sidechain A compressor or a gate can follow the level of another signal instead of its own: a kick ducks a pad, a voice ducks the music. Switch **Sidechain** on, and connect the signal to `engine.sidechain`. It is only listened to, never heard. ```ts const engine = createCompressorEngine(ctx, { ...state, external: true }); pad.connect(engine.input); kick.connect(engine.sidechain); // listened to, not heard engine.output.connect(ctx.destination); ``` The sidechain is not a parameter. The state holds the switch and the host routes the signal. A device that takes one says so: `compressorDevice.sidechain` is `true`, and so is `describe().sidechain`, so a host knows to route something to it and an agent can be told. With the sidechain on, what the device does depends on the other signal, so its panel does not draw a transfer curve. ## Tempo sync A delay, a chorus, a phaser and an auto pan can take their time or their rate from a note value, such as `1/8`, a triplet `1/8t` or a dotted `1/8d`, from 1/32 to a whole note. Switch **Sync** on and pick a **Note**. The tempo is the host's, not the device's: give it to the engine with the first state or with any update. ```ts const engine = createDelayEngine(ctx, state, { tempo }); // { bpm: 100, beatsPerBar: 4, beatUnit: 4 } engine.update(nextState, { tempo: { ...tempo, bpm: 120 } }); // the echo follows engine.update(otherState); // no context: the last tempo holds ``` The panel takes the same tempo as a prop, `tempo`. With Sync on, the knob for the free value is drawn off; with it off, the list of notes is. A tool call can switch Sync on and pick a note, but it never sets the tempo. ## Latency Some devices delay the signal. `device.latency(state, sampleRate)` returns it in seconds, so a host can compensate. The dry path waits as long as the wet one, so a partial mix does not comb. | Device | Latency | Why | | --- | --- | --- | | Compressor | 6 ms | The look-ahead of the browser's compressor node. | | Limiter | 10 ms | The look-ahead of the node and the 4x oversampling of the clip. | | Distortion, overdrive, saturator, wave shaper | 4 ms | The 4x oversampling of the shaper, 192 samples at 48 kHz. | | Transient shaper | 1 ms | The audio waits for the detector. | | Gate | The look-ahead you set | Up to 10 ms, 0 by default. | Every other device has none. The numbers were measured in Chrome and the specification does not give them, so measure them in another browser with `measureLatency`. ## Readings A device that takes gain off the signal says how much, through `readings()` on its engine, in dB, 0 or negative. A meter reads it per frame, in the same way for every device: the compressor, the limiter and the de-esser report the gain they take, and the multiband device one value per band. ```ts const { gainReductionDb } = engine.readings(); // compressor, limiter, de-esser const { bandGainReductionDb } = multibandEngine.readings(); // low, mid, high ``` A device with no gain to take off has no `readings()`, and a host that draws a meter for it draws none. ## Tools The tools are derived from the parameters of the device, with a JSON Schema input, so any agent can use them. They are not tied to an SDK. ```ts import { deviceTools } from "@audio-ui/core/device"; const [set, reset] = deviceTools(compressorDevice); // set.name === "audioui_compressor_set" const { state: next, summary } = set.run(state, { thresholdDb: -300, ratio: "high" }); // summary: "Threshold: -18.0 dB to -60.0 dB (brought into range); ratio: refused, not a number" ``` `set` changes parameters and `reset` puts them back to their defaults. An instrument adds a `play` tool that gives the host a note to start. The ranges a model is told are the ones the device enforces. A value out of range is brought in and reported, a value of the wrong type is refused by name and never replaced by a default, and a call never throws. The summary is the answer to give back to the model. ## Measure your engine A host that brings its own engine can check it against what the panel draws. `device-measure` renders an engine in an offline audio context and compares it with the curve of the device. It works for any device whose curve is a frequency response, such as the equalizer, the filter and the channel EQ. ```ts import { equalizerCurve, equalizerDevice } from "@/components/audio-ui/devices/equalizer/device"; import { measureLatency, measureResponse } from "@/lib/device-measure"; const state = equalizerDevice.defaults(); // Your factory: (ctx, state) => { input, output, dispose }. const { worstDb, at } = await measureResponse(createMyEngine, state, equalizerCurve(state)); // worstDb: how far your engine is from the panel, in dB, and where (at, in Hz). const latencyMs = await measureLatency(createMyEngine, state); // What a host reports to compensate it. ``` It is a measurement, not a certification: the curve is the device's own and the tolerance is yours. ## Your own device `defineDevice` is the one extension point, and the core keeps no list of devices. A device you define gets the same panel, tools and bindings as the ones here. ```tsx import { defineDevice } from "@audio-ui/core/device"; import { DevicePanel } from "@/components/audio-ui/device-panel"; const tremolo = defineDevice({ id: "acme.tremolo", name: "Tremolo", description: "Moves the level up and down.", parameters: [ { id: "on", kind: "toggle", label: "Active", default: true }, { id: "rate", label: "Rate", min: 0.5, max: 20, scale: "log", step: 0.5, unit: "Hz", default: 5 }, { id: "depth", label: "Depth", min: 0, max: 100, step: 1, unit: "%", default: 50 }, ], }); ; ``` `DevicePanel` makes a knob for each number, a toggle for each switch and a row of buttons for each choice, such as a waveform or a filter type. A face of your own, such as a curve or a spectrum, is optional. An instrument is the same with `kind: "instrument"`. Its parameters shape the sound, and its engine adds `noteOn` and `noteOff` next to `update`. The [pocket synth](/docs/components/base/pocket-synth) is the example: its panel is controlled and sends notes out, so it plays through any engine. ## Your own engine A host that has its own audio engine, such as a DAW with one in a worklet, keeps the state and the panel and turns the state into its own messages. A `DeviceBinding` is just that: ```ts import type { DeviceBinding } from "@audio-ui/core/device"; const binding: DeviceBinding = { update: (state) => engine.post({ type: "compressor", ...compressorSettings(state) }), dispose: () => engine.post({ type: "compressor-off" }), }; ``` ## Accessibility Every control is a native input. A knob is a slider named after its parameter, with its value and unit as the text value ("Threshold, -18.0 dB"), and a switch is a toggle button. A panel is a group named after the device. The curve is decoration around the controls, a handle on it is a slider, and everything takes the keyboard. --- # Installation > A quick guide to adding audio/ui components to your application. This guide shows how to add audio/ui to a shadcn project. If you do not use shadcn/ui, install the headless primitives with `npm install @audio-ui/react` instead, see the [Introduction](/docs). ## Prerequisites audio/ui is built on **React 19** and [Tailwind CSS v4](https://tailwindcss.com). Set up both first. The [shadcn/ui installation guide](https://ui.shadcn.com/docs/installation) covers the environment. ## Setup the audio/ui Registry Add the audio/ui registry namespace to your `components.json` and set your component library and style. See the [shadcn registry docs](https://ui.shadcn.com/docs/registry) for the registry config. ```json { "registries": { "@audio-ui": "https://www.audio-ui.dev/r/{style}/{name}.json" } } ``` ## Components You can install audio/ui using the [**shadcn CLI**](https://ui.shadcn.com/docs/cli) for automation or by manual installation for full control. Both methods apply to everything in [Docs](/docs/) and the [component catalog](/components), including the `block-*` blocks and demos you install with `@audio-ui/…`. ### The package a component needs Some components import from `@audio-ui/core` (pitch, MIDI, musical time, analysis). Installing one adds the package to your `package.json` if it is not there, with no version pinned: the version is yours to choose. The CLI leaves a version you already have. If an older `@audio-ui/core` is installed and a component needs a subpath it did not have yet, your build says it cannot resolve `@audio-ui/core/time` (or `/pitch`, `/midi`, `/analysis`). Update the package: ```bash npm install @audio-ui/core@latest ``` If your package manager still resolves the old version, bypass its cache: with Bun, add `--no-cache`. ## Styling Components are styled with a design token system defined by CSS variables and implemented with Tailwind CSS, following the same conventions as shadcn/ui so they're fully customizable. See the [Styling guide](/docs/styling) for details. ## Work with an AI agent Give your agent the [Agent skill](/docs/agents) and connect the [MCP server](/docs/mcp), so it picks the right component and reads the docs live. Every docs page is also served as markdown, with a Copy Markdown button, and [llms.txt](/llms.txt) maps them all. ## Next Steps Head over to the [Knob](/docs/components/base/knob) docs to install your first component, or browse the [component catalog](/components) for ready-to-use blocks. --- # Headless styling > How to style the primitives of @audio-ui/react with nothing but CSS: each part exposes its state as data attributes and its live values as CSS variables, and the reference below lists them for every primitive. The primitives paint nothing: no colour, no size, no theme. What a part looks like comes from your CSS, and the part gives that CSS everything it needs: its state as attributes, and what changes too often to be an attribute as a variable. A skin needs no React state of its own. ## Style from the state A part carries its state on the element. A knob that is being dragged has `data-dragging`, a disabled fader `data-disabled`, a fader a `data-orientation`. Select on them: ```css .my-knob [data-dragging] { box-shadow: 0 0 0 4px color-mix(in oklab, currentColor 20%, transparent); } .my-knob [data-disabled] { opacity: 0.4; } ``` A boolean that is off has no attribute, so the absence is a state too: `:not([data-active])` styles the rest. ## Style from the variables What changes on every frame is a CSS variable, set on the element, not an attribute, so the browser does not re-match selectors on each change. A knob's mark turns with `--knob-mark-angle`, a pad's crosshair moves with `--xy-pad-x` and `--xy-pad-y`: ```css .my-knob-mark { transform: rotate(var(--knob-mark-angle)); } ``` ## What stays inline Three styles are behaviour, not look, and each part sets them itself: - `touch-action: none` on a surface that is dragged, so a touch drags the control and does not scroll the page. - `position: relative` on a container that holds parts placed absolutely, such as a fader's mark or a knob's arc, so those parts sit in the container and not on the page. - `pointer-events: none` on decoration that must not take the pointer. A stylesheet can still change anything else about them. The behaviour of these three is the primitive's contract. An inline style beats any class, so a class cannot change them. To place a part itself, say an envelope at the corner of a panel, pass the `style` prop: it is applied after the part's own, so `style={{ position: "absolute", top: 8 }}` wins. In a skin of CSS alone, put the part in an element you position. What a part sets inline for its value, such as a thumb's `left` and `translate` or an indicator's `height`, is the value itself: a class does not replace it, it adds to it. ## Give each part a size A part has no size of its own, and one that sits at a position along a line or a plane does not lay itself out: it needs a box, and for a part placed with `bottom`, `left` or `inset`, `position: absolute`. These are the least that draws each of the five controls below, from the part names of their anatomy: ```css /* Fader: the control is the box, the thumb sits at the value */ .fader-control { width: 2rem; height: 8rem; } .fader-track { width: 0.5rem; height: 100%; margin-inline: auto; background: #333; } .fader-indicator { position: absolute; background: #6cf; } .fader-thumb { width: 1.5rem; height: 0.75rem; background: #eee; } /* XYPad: the control is the surface */ .xypad-control { width: 8rem; height: 8rem; background: #222; } .xypad-thumb { position: absolute; width: 1rem; height: 1rem; border-radius: 50%; background: #6cf; } /* Knob: the arcs are SVGs that fill the control, one over the other */ .knob-control { width: 4rem; height: 4rem; } .knob-track, .knob-indicator { position: absolute; inset: 0; width: 100%; height: 100%; } .knob-track { color: #333; } .knob-indicator { color: #6cf; } .knob-thumb { position: absolute; inset: 0; } /* turns with the value */ .knob-thumb::after { content: ""; position: absolute; top: 12%; left: 50%; width: 2px; height: 28%; background: #eee; transform: translateX(-50%); } /* Meter: the channel is the bar, the indicator is scaled to the level */ .meter { height: 8rem; display: flex; gap: 2px; } .meter-channel { width: 0.75rem; height: 100%; background: #222; } .meter-indicator { position: absolute; bottom: 0; background: #6c6; } /* Plot: the root is the box, the graph fills it */ .plot { width: 12rem; height: 6rem; background: #222; } .plot-line { stroke: #6cf; } ``` Each class goes on the part it is named after, with `className`. Sizes are in your units and colours are yours; what matters is which part takes which rule. ## Reference Generated from the source of each primitive: the data attributes of the state each part exposes, and the CSS variables it sets. A value of the state of a plain type (a boolean, a number, a string) is an attribute, unless the primitive keeps it off the element. A callback or an object is not. {/* reference:start */} ### Envelope State on every part that takes it: `data-disabled`, `data-dragging`. | Part | Data attributes | CSS variables | | --- | --- | --- | ### Fader State on every part that takes it: `data-disabled`, `data-dragging`, `data-orientation`. | Part | Data attributes | CSS variables | | --- | --- | --- | ### Knob State on every part that takes it: `data-disabled`, `data-dragging`. | Part | Data attributes | CSS variables | | --- | --- | --- | | `Mark` | | `--knob-mark-angle` | ### Meter | Part | Data attributes | CSS variables | | --- | --- | --- | | `Root` | `data-clipped` | | ### Pad State on every part that takes it: `data-columns`, `data-disabled`. | Part | Data attributes | CSS variables | | --- | --- | --- | | `Item` | | `--pad-velocity` | ### Piano State on every part that takes it: `data-disabled`, `data-max-pitch`, `data-min-pitch`, `data-orientation`. | Part | Data attributes | CSS variables | | --- | --- | --- | ### Piano-roll State on every part that takes it: `data-disabled`, `data-draw-style`, `data-folded`, `data-max-pitch`, `data-min-length`, `data-min-pitch`, `data-mode`. | Part | Data attributes | CSS variables | | --- | --- | --- | | `Root` | `data-has-selection` | | | `Rows` | `data-in-scale` | | ### Plot State on every part that takes it: `data-disabled`, `data-max-x`, `data-max-y`, `data-min-x`, `data-min-y`. | Part | Data attributes | CSS variables | | --- | --- | --- | | `Cursor` | `data-active` | `--plot-cursor-x`, `--plot-cursor-y` | ### Sequencer State on every part that takes it: `data-disabled`. | Part | Data attributes | CSS variables | | --- | --- | --- | | `Root` | `data-current`, `data-painting` | | | `Velocity` | | `--sequencer-velocity` | ### Timeline State on every part that takes it: `data-default-position`, `data-default-zoom`, `data-disabled`, `data-duration`, `data-large-step`, `data-max-zoom`, `data-min-zoom`, `data-position`, `data-snap-offset`, `data-snap-step`, `data-step`, `data-value`, `data-zoom`. | Part | Data attributes | CSS variables | | --- | --- | --- | | `ClipFade` | | `--clip-fade-in`, `--clip-fade-out` | | `Clip` | | `--clip-drag-y`, `--clip-fade-in`, `--clip-fade-in-max`, `--clip-fade-out`, `--clip-fade-out-max`, `--clip-offset`, `--clip-source-length` | | `Lane` | `data-timeline-lane` | | | `Viewport` | `data-timeline-viewport` | | ### Waveform | Part | Data attributes | CSS variables | | --- | --- | --- | | `Bars` | `data-index`, `data-played` | `--waveform-level` | | `Canvas` | `data-theme` | `--waveform-bar-radius`, `--waveform-color`, `--waveform-progress-color` | | `Root` | `data-active`, `data-outside` | | ### Xypad State on every part that takes it: `data-disabled`, `data-dragging`. | Part | Data attributes | CSS variables | | --- | --- | --- | | `Root` | | `--xy-pad-x`, `--xy-pad-y` | {/* reference:end */} --- # Icons > The glyphs audio/ui draws for itself: one thin stroke on a 24 grid, in four weights, named for what they draw. Search them, pick a weight and a size, then copy the SVG. Audio has things a general icon set does not draw: a knob, a rack unit, the shape of a sawtooth, the response of a high shelf. These glyphs are audio/ui's own, drawn to sit together and to take the color of the text around them. | Icon | Component | Category | Keywords | | --- | --- | --- | --- | | Knob | `KnobIcon` | Controls | control, dial, rotary, parameter | | Tracks | `TracksIcon` | Editors | arrangement, clips, timeline, daw | | Rack | `RackIcon` | Effects | device, plugin, effect, unit | | Faders | `FadersIcon` | Controls | mixer, levels, channels, sliders | | Waveform | `WaveformIcon` | Displays | engine, signal, bars, meter | | Envelope | `EnvelopeIcon` | Editors | adsr, automation, curve | | XYPad | `XYPadIcon` | Controls | pad, two values, position, xy | | Pad | `PadIcon` | Controls | drum, trigger, strike, velocity | | Piano | `PianoIcon` | Controls | keyboard, keys, notes | | Meter | `MeterIcon` | Displays | level, peak, vu, bar | | Gauge | `GaugeIcon` | Displays | needle, vu, dial, tuner | | Spectrum | `SpectrumIcon` | Displays | analyzer, frequency, fft, bars | | Scope | `ScopeIcon` | Displays | oscilloscope, signal, trace | | Plot | `PlotIcon` | Displays | graph, curve, axes, eq | | Play | `PlayIcon` | Transport | start, run | | Pause | `PauseIcon` | Transport | hold | | Stop | `StopIcon` | Transport | halt, end | | Record | `RecordIcon` | Transport | arm, capture | | Loop | `LoopIcon` | Transport | repeat, cycle, region | | Mic | `MicIcon` | Signal | microphone, input, voice | | Speaker | `SpeakerIcon` | Signal | output, monitor, loudspeaker | | Headphones | `HeadphonesIcon` | Signal | output, cue, monitor | | Midi | `MidiIcon` | Signal | din, keyboard, controller, plug | | Sequencer | `SequencerIcon` | Editors | steps, pattern, drum machine | | PianoRoll | `PianoRollIcon` | Editors | notes, midi, editor | | Compressor | `CompressorIcon` | Effects | dynamics, curve, knee, ratio | | Delay | `DelayIcon` | Effects | echo, repeat, feedback | | Reverb | `ReverbIcon` | Effects | room, space, tail | | Distortion | `DistortionIcon` | Effects | overdrive, clip, saturation | | Stereo | `StereoIcon` | Signal | channels, left right, width, pan | | Mono | `MonoIcon` | Signal | one channel, centre, summed, single | | Tape | `TapeIcon` | Signal | cassette, reel, recording, lo-fi | | Vinyl | `VinylIcon` | Signal | record, disc, turntable, dj | | Clip | `ClipIcon` | Editors | region, audio, waveform, arrangement | | Automation | `AutomationIcon` | Editors | points, line, parameter, envelope | | Magnet | `MagnetIcon` | Editors | snap, grid, quantize | | Sine | `SineIcon` | Oscillators | wave, oscillator, smooth | | Square | `SquareIcon` | Oscillators | wave, oscillator, pulse | | Sawtooth | `SawtoothIcon` | Oscillators | wave, oscillator, saw, ramp | | Triangle | `TriangleIcon` | Oscillators | wave, oscillator | | Lowpass | `LowpassIcon` | Filters | filter, cut, response | | Highpass | `HighpassIcon` | Filters | filter, cut, response | | Bandpass | `BandpassIcon` | Filters | filter, band, response | | Notch | `NotchIcon` | Filters | filter, reject, response | | Lowshelf | `LowshelfIcon` | Filters | filter, eq, shelf, bass | | Highshelf | `HighshelfIcon` | Filters | filter, eq, shelf, treble | | Peak | `PeakIcon` | Filters | filter, eq, bell, band | | Metronome | `MetronomeIcon` | Transport | start, begin, count in, tempo, get started | | TuningFork | `TuningForkIcon` | Docs | introduction, about, reference, pitch | | Jack | `JackIcon` | Signal | install, installation, plug, connect | | Patchbay | `PatchbayIcon` | Signal | registry, sockets, patch, panel | | Shapes | `ShapesIcon` | Docs | primitives, circle, square | | Braces | `BracesIcon` | Docs | code, headless, css, curly | | Fader | `FaderIcon` | Controls | theme, tokens, values, mixer | | Playhead | `PlayheadIcon` | Editors | roadmap, timeline, plan, transport | | Grid | `GridIcon` | Docs | catalog, icons, tiles | | Note | `NoteIcon` | Docs | introduction, music, welcome, overview | | Insert | `InsertIcon` | Docs | install, installation, add, rack | | Crate | `CrateIcon` | Docs | registry, catalog, records, collection | | Dial | `DialIcon` | Docs | headless, unstyled, skeleton, knob | | Contrast | `ContrastIcon` | Docs | theme, tokens, light, dark | | Sparkle | `SparkleIcon` | Agents | ai, skill, magic, star | | Bot | `BotIcon` | Agents | llm, robot, assistant | ## Weights Each glyph comes in four weights, picked with the `weight` prop of its icon: - `regular` is the thin line, 1.5 on the 24 grid. It is the default. - `bold` is a thicker line, 2.25, for a small size or a state to show. - `duotone` is the line over a tint of the same color. Closed shapes take the tint; a glyph made of lines has a soft shape behind it. - `fill` is the solid shape, with its details cut out of it. A glyph made of lines only has no body to fill, so it is drawn as the bold line. ## Use them The icons are in `@audio-ui/icons`, on npm. Install it, and an icon is a React component named for what it draws, with `Icon` after: `KnobIcon`, `TracksIcon`, `SineIcon`, `LowpassIcon`. It is `1em` wide unless `size` says otherwise, and it takes the color of its text. ```sh npm install @audio-ui/icons ``` ```tsx import { KnobIcon } from "@audio-ui/icons/react"; ; ``` The package works without React. `@audio-ui/icons` holds the glyphs as data, the catalog and `toSvg`, which gives the text of an SVG file for any glyph in any weight; `draw` gives the same drawing as plain nodes, for a Vue, Svelte or custom element adapter to render. **Copy SVG** and **Download** on this page give the same text. ## Draw one A new glyph is a few shapes on a 24 grid with a 2px margin, drawn with one stroke width and round ends. Mark a closed shape as tinted so it has a body in `duotone` and `fill`, and a detail inside it as a knock so `fill` cuts it out. The package's tests draw every glyph in every weight, so a glyph that breaks one fails them. --- # Introduction > Accessible audio controls for React, as headless primitives on npm and as styled components you copy into your shadcn/ui project. Built to be used by people and by AI agents. **audio/ui** is a set of accessible, composable audio controls for React: knobs, faders, XY pads, envelopes, meters, waveforms, timelines, sequencers, drum pads, piano keyboards and piano rolls. Audio controls have many details: a knob has to drag, respond to the wheel and the keyboard, reset on double click, and be announced correctly by a screen reader. audio/ui implements them once. ## Two layers Use the layer that fits your project. They share the same behavior. **`@audio-ui/react`** are headless primitives from npm: behavior and accessibility, no styles. Pick them when you have your own design system. ```bash npm install @audio-ui/react ``` **The `@audio-ui` registry** holds styled components and ready blocks that you copy into your code and own. Pick it when you use shadcn/ui and Tailwind CSS v4. ```bash npx shadcn@latest add @audio-ui/knob ``` Both are open source. With the registry you receive the actual code, so you can read it, change it and learn from it. ## Top components Each links to its docs, with a live preview, the API and the source. Install any of them with `npx shadcn@latest add @audio-ui/`. **Top components** | Name | Description | | --- | --- | | `Knob` | Rotary parameter with drag, wheel, keyboard and reset. [Docs](/docs/components/base/knob). | | `Fader` | Linear gain or parameter slider. [Docs](/docs/components/base/fader). | | `XY Pad` | Two parameters on one surface. [Docs](/docs/components/base/xypad). | | `Envelope` | Breakpoint editor for ADSR and other ramps. [Docs](/docs/components/base/envelope). | | `Meter` | Stereo and multi-channel level with peak hold. [Docs](/docs/components/base/meter). | | `Waveform` | Seekable, live or bar-style waveform with regions. [Docs](/docs/components/base/waveform). | | `Plot` | Draggable curves for EQs, filters and compressors. [Docs](/docs/components/base/plot). | | `Timeline` | Zoomable arrangement view with a smooth playhead. [Docs](/docs/components/base/arrangement). | | `Sequencer` | Step grid to draw a pattern. [Docs](/docs/components/base/sequencer). | | `Pad` | Drum pads with velocity and choke groups. [Docs](/docs/components/base/pad). | | `Piano Roll` | DAW-style note editor with a velocity lane. [Docs](/docs/components/base/piano-roll). | Looking for a whole screen? The [component catalog](/components) has composed blocks (a pocket synth, a wave shaper, a waveform player) you can install the same way. ## Built for agents audio/ui is made to be used by AI coding agents as much as by people. Open code, one consistent API and plain markdown docs mean an agent can find the right component, read how it works and wire it up without guessing. - **[Agent skill](/docs/agents):** teaches your agent which layer to pick, how to install and the mistakes to avoid. - **[MCP server](/docs/mcp):** `https://www.audio-ui.dev/mcp` lets your agent list components, read their docs and search the catalog. - **[llms.txt](/llms.txt):** a structured map of every docs page, each also served as markdown. ## Principles - **Accessible by default:** native inputs where it matters, labelled controls, full keyboard support. - **Composable:** small parts that fit together, so you pick the level of abstraction for each screen. - **Open code:** read it, change it, own it. - **No lag:** values that change every frame, like playheads and meters, move without re-rendering your page. ## Next steps Head over to [Get started](/docs/get-started) to add audio/ui to your project, or open [Knob](/docs/components/base/knob) to install your first component. --- # MCP > Connect your AI agent to audio/ui with the MCP server, to list components, read their docs and search the catalog. MCP is an open protocol that lets AI agents use tools. The audio/ui MCP server gives your agent access to every component and its current docs. The server is remote, needs no account and no install: ``` https://www.audio-ui.dev/mcp ``` ## Connect your client **Claude Code** ```bash claude mcp add --transport http audio-ui https://www.audio-ui.dev/mcp ``` **Cursor** Add this to `.cursor/mcp.json`: ```json { "mcpServers": { "audio-ui": { "url": "https://www.audio-ui.dev/mcp" } } } ``` **VS Code** Add this to `.vscode/mcp.json`: ```json { "servers": { "audio-ui": { "type": "http", "url": "https://www.audio-ui.dev/mcp" } } } ``` **Other** Any client that supports remote servers over Streamable HTTP works. Add a server of type `http` with the URL above. ## Tools **Tools** | Name | Description | | --- | --- | | `search_docs` | Search the docs text in plain words. Each hit names a component and a section to read next. | | `list_components` | All components with docs URL and install command, or one `kind`: elements, workstation or devices. | | `get_component_docs` | One component's docs as markdown, or one section of them with `section`. A reply over 25,000 characters is cut, and says which sections to ask for. | | `search_catalog` | Find ready-made blocks by words like `synth`, 25 per page. Pass `next_offset` as `offset` for the next page. | ## Usage Ask your agent in plain words: - Build a synth control panel with Knob, XY Pad and Fader. - Add an equalizer with a Plot and draggable band handles. - Make a piano roll with a keyboard, a velocity lane and a loop range. ## With shadcn Because audio/ui is also a shadcn registry, the shadcn MCP server can install components too. Run `npx shadcn@latest mcp init` and add the `@audio-ui` registry from the [Registry guide](/docs/registry). For the best results, also install the [agent skill](/docs/agents). --- # Primitives > How the headless primitives of @audio-ui/react are put together, styled, controlled and read, the same way for every one of them. All primitives in `@audio-ui/react` share one structure. The Knob shows it, and the others follow the same pattern. ## Parts A primitive is a set of parts you assemble. Each part renders one element and does one job: the root owns the value, the control takes the pointer, the thumb takes the focus. ```tsx import { Knob } from "@audio-ui/react"; Cutoff ``` Nothing is painted: no colour, size or theme comes from a primitive. Each part sets only the inline styles its behaviour needs (`touch-action` on a drag surface, `position: relative` on a container that holds absolutely placed parts, `pointer-events` on decorations), and the look is yours. Parts you leave out are not rendered, so a knob with no value readout is a knob without `Knob.Value`. ## Style from state State is on the element, never behind a prop you have to read. Style it with the attribute selectors of your CSS or the variants of your framework: ```tsx ``` - **Attributes and variables.** A part has `data-disabled`, `data-dragging` and the like when they are true, and no attribute when they are not. What changes too often to be an attribute is a CSS variable, such as a knob mark's angle or a timeline's unit. [Headless styling](/docs/headless-styling) lists both for every part. - **State functions.** `className` and `style` can be functions of the part's state: ```tsx (state.dragging ? "ring-2" : "ring-0")} /> ``` ## Render another element Every part takes a `render` prop to change the element it renders or to compose it with your own component. Its props, ref and handlers are merged with yours, not replaced: ```tsx } />
} /> ``` A handler you pass runs alongside the part's own. A consumer's `onPointerDown` does not switch the drag off. ## Control the value A primitive is uncontrolled with `defaultValue`, or controlled with `value`. Either way it tells you what changed and why: ```tsx { if (eventDetails.reason === "wheel") { eventDetails.cancel(); // refuse this one } }} onValueCommitted={(value, eventDetails) => save(value)} value={cutoff} /> ``` - `onValueChange` fires on every change, with `eventDetails.reason` (`"drag"`, `"wheel"`, `"keyboard"`, `"reset"`, `"input-change"`...) and `eventDetails.event`, the event behind it. `eventDetails.cancel()` refuses the change: a controlled value stays put, an uncontrolled one does not move. - `onValueCommitted` fires once, when a gesture that changed the value ends. That is the time to start a note, push to an undo stack or save, not on every move of a drag. - While a pointer drags, the part follows it even if your controlled value is late, and takes the value back when the pointer is released. ## Live values A playhead, a meter or a waveform that follows a signal changes sixty times a second, too often to go through React state. Give it a `source` instead, an object with `getSnapshot` and `subscribe`, and the part writes each value straight to the DOM: ```tsx import { createSource } from "@audio-ui/react"; const position = createSource(0); // in your audio loop position.set(audioContext.currentTime); ``` Your page does not re-render while it plays. ## Accessibility Each control holds a native ``, visually hidden. It takes the focus, answers the arrow, Page, Home and End keys, announces its value and carries the accessible name, so a screen reader and the keyboard treat it as the slider it is. Give the thumb an `aria-label`, or a `Label` part, and format what is read out with `getAriaValueText` or `format`. Pointer presses do not draw the keyboard focus ring; keyboard focus does. ## Import only what you use Import from the root, or from a subpath to keep the rest out of your bundle: ```tsx import { Knob } from "@audio-ui/react/knob"; ``` A single primitive weighs a few kilobytes gzipped (a knob about 5 KB, a fader about 3 KB). ## Forms The parameter controls are form fields. Give one a `name` and its native input submits with the form, so a preset can be a plain `
`: ```tsx ... ... ...
``` - **Knob and Fader** submit one number under their `name`. The Knob also takes `form` to belong to a form elsewhere in the page. - **XY Pad** submits two, as `pad.x` and `pad.y`. - The other primitives (Envelope, Plot, Sequencer, Pad, Piano, PianoRoll, Timeline, Waveform, Meter) hold a value that is not a single number, a curve or a pattern for instance, so they do not submit by themselves: read it from `onValueChange` or `onValueCommitted` and send it as you like. - A disabled control is left out of the submission, as with any input. --- # Registry > Learn how to use the audio/ui Registry with shadcn/ui. The audio/ui registry adds audio components and blocks to a shadcn/ui project. Add the namespace once, then install any item by name. ## Setup Add the `@audio-ui` namespace to your `components.json` once: [Installation](/docs/get-started#setup-the-audioui-registry) has the line, and the prerequisites. ## Usage Install blocks via the shadcn CLI using the `@audio-ui/{name}` syntax. ```bash npx shadcn@latest add @audio-ui/block-pocket-synth ``` Install components via the shadcn CLI using the `@audio-ui/{name}` syntax. ```bash npx shadcn@latest add @audio-ui/knob ``` --- # Roadmap > What audio/ui ships today, and what comes next. **audio/ui** is a toolkit for building audio interfaces in React: headless primitives on npm (`@audio-ui/react`) and styled components for [shadcn/ui](https://ui.shadcn.com/) that you copy, paste and customize. ## Current Status Available today: ### Elements The pieces of any audio interface: - **Controls**: Knob, Fader, XY Pad and Envelope, with scales, rulers and fine drag - **Keyboards and pads**: Piano and Pad - **Displays**: Meter and Needle meter (a VU dial to the standard), Waveform, from peaks, a live signal or a range of the audio, Plot, for curves and draggable points, Spectrum analyzer and Tuner ### Workstation The surfaces of a DAW, controlled and independent of any audio engine: - **Arrangement**: Timeline, a zoomable ruler with lanes, ranges and a navigator, and the arrangement editor on top of it: tracks of clips, selection, time commands, mixes, tempo, signatures, locators, loop and undo - **Editors**: Piano Roll, with scales, edits, lanes and a MIDI file in and out, and Sequencer - **Piano roll tools**: Scale menu, Note find and Note edit menu - **Transport**: Transport and Scrubber - **Mixing**: Mixer, and the device chain: a track's devices in a row, each drawn by its own panel, with a library to add one from ### Devices 22 effects and instruments, each a definition, a Web Audio engine and a panel generated from its parameters: dynamics (compressor, multiband, limiter, gate, de-esser, transient shaper), tone (equalizers and a filter), distortion, space and modulation (delay, reverb, chorus, phaser, auto pan), and utility and two instruments. A device reports what it takes off the signal for a meter, and exposes tools for an agent. See [Devices](/docs/devices). ### Audio engine The hooks and libraries on the Web Audio API that make the sound, for the components that need it: output, clock and time, synthesis, input and analysis, and the controllers of `@audio-ui/core` for use with no framework. An engine of your own can drive the same components. See [Audio engine](/docs/engine). ### Blocks Pre-assembled patterns: a mixing console, a drum rack, a piano roll, a timeline, a waveform player, and a block for each device. Browse the [component catalog](/components). ### For agents - **[MCP server](/docs/mcp)**: list components, read their docs and search the catalog from your agent - **[Agent skill](/docs/agents)**: teaches your agent which layer to pick and how to wire each component ## What's Next - **Adapters beyond React**: the controllers of `@audio-ui/core` already drive a control with no framework, so the next step is to package that: custom elements over the controllers, and Vue and Svelte adapters, each one kept in step with the React primitives. How many to maintain is still to decide. A page would show one knob and one fader in React, Vue, Svelte and a web component, all on the same store and in sync. - **Agents**: the Agent Skill and the MCP server have a link on the home page and a page each. They should be easier to find, from the documentation overview and from the component pages, with what an agent gets from each in a few lines. - **Devices**: a device is a definition, an engine and a panel, and the panel is generated from the parameters alone, with no code of its own per device. That is shown on the Devices page as one device in two skins; it should be shown as the idea it is, with the contract (the parameters, the readings, the tools for an agent) in plain view. - **More audio components**: further audio-specific patterns and controls. ## Contributing We're building this in the open and welcome contributions! Whether it's bug reports, feature requests, or code contributions, we'd love to have you involved. Check out our [GitHub repository](https://github.com/ouestlabs/audio-ui) to get started. --- # Theme tokens > The semantic color tokens audio/ui adds to the shadcn/ui theme, for states such as alerts and badges. ## Overview audio/ui adds semantic color tokens to the shadcn/ui theme, for states such as alerts and badges. To style the headless primitives with your own CSS, see [Headless styling](/docs/headless-styling). Standard shadcn/ui themes work too. The custom tokens keep contrast consistent across these states. ## Extended Tokens To support advanced state communication, we extend the base palette with additional semantic tokens: - `--destructive-foreground`: Foreground color specifically for destructive actions. - `--info` & `--info-foreground`: Background and text colors for informational states. - `--success` & `--success-foreground`: Background and text colors for success/positive outcomes. - `--warning` & `--warning-foreground`: Background and text colors for cautionary states. - `--invert` & `--invert-foreground`: Background and text colors for invert states. ```css title="app/globals.css" @theme inline { --color-destructive-foreground: var(--destructive-foreground); --color-info: var(--info); --color-info-foreground: var(--info-foreground); --color-success: var(--success); --color-success-foreground: var(--success-foreground); --color-warning: var(--warning); --color-warning-foreground: var(--warning-foreground); --color-invert: var(--invert); --color-invert-foreground: var(--invert-foreground); } :root { --destructive-foreground: var(--color-red-800); --info: var(--color-violet-500); --info-foreground: var(--color-violet-900); --success: var(--color-emerald-500); --success-foreground: var(--color-emerald-900); --warning: var(--color-yellow-500); --warning-foreground: var(--color-yellow-900); --invert: var(--color-zinc-900); --invert-foreground: var(--color-zinc-50); } .dark { --destructive-foreground: var(--color-red-600); --info: var(--color-violet-500); --info-foreground: var(--color-violet-600); --success: var(--color-emerald-500); --success-foreground: var(--color-emerald-600); --warning: var(--color-yellow-500); --warning-foreground: var(--color-yellow-600); --invert: var(--color-zinc-700); --invert-foreground: var(--color-zinc-50); } ``` For general customization guidelines such as adding your own custom colors or switching between utility classes and variables, please refer to the [official shadcn/ui documentation](https://ui.shadcn.com/docs/theming). --- # Auto pan > An auto pan device: a pan or tremolo mode, a wave shape, a rate or a note value and a depth, a panel that draws the movement, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { AutoPanPanel } from "@/components/audio-ui/devices/auto-pan/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type AutoPanState, autoPanDevice, } from "@/components/audio-ui/devices/auto-pan/device"; import { createAutoPanEngine } from "@/components/audio-ui/devices/auto-pan/engine"; const MASTER_VOLUME = 0.7; /** Sways on the half note: one cycle every two beats of the loop. */ const START = { division: "1/2", sync: true }; /** * An auto pan you can plug in: its state, a panel that draws the movement and an engine that plays it, each its own file. Play the loop, pick a waveform and switch to tremolo. */ export function BlockAutoPan() { const [state, setState] = useState( () => autoPanDevice.apply(autoPanDevice.defaults(), START).state ); const master = useMasterBus(MASTER_VOLUME); const { tempo } = useDeviceLoop({ create: createAutoPanEngine, destination: master, state, }); return (
); } ``` Moves the sound with a slow oscillator. In Pan mode it moves from one speaker to the other. In Tremolo mode its level goes up and down. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/auto-pan ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/auto-pan/`. The demo above, which wires them to a loop, is `@audio-ui/block-auto-pan`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/auto-pan-device @audio-ui/auto-pan-panel @audio-ui/auto-pan-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-auto-pan.tsx" "use client"; import { useState } from "react"; import { AutoPanPanel } from "@/components/audio-ui/devices/auto-pan/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type AutoPanState, autoPanDevice, } from "@/components/audio-ui/devices/auto-pan/device"; import { createAutoPanEngine } from "@/components/audio-ui/devices/auto-pan/engine"; const MASTER_VOLUME = 0.7; /** Sways on the half note: one cycle every two beats of the loop. */ const START = { division: "1/2", sync: true }; /** * An auto pan you can plug in: its state, a panel that draws the movement and an engine that plays it, each its own file. Play the loop, pick a waveform and switch to tremolo. */ export function BlockAutoPan() { const [state, setState] = useState( () => autoPanDevice.apply(autoPanDevice.defaults(), START).state ); const master = useMasterBus(MASTER_VOLUME); const { tempo } = useDeviceLoop({ create: createAutoPanEngine, destination: master, state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the auto pan from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Mode | Pan, Tremolo | Pan | Pan moves the sound between the speakers, Tremolo moves its level. | | Shape | Sine, Triangle, Saw, Square | Sine | The wave of the oscillator: sine, triangle, saw or square. | | Rate | 0.05 Hz to 20.00 Hz | 1.00 Hz | How fast the oscillator moves. | | Sync | On or off | Off | Takes the rate from a note value and the tempo of the host. See [Tempo sync](/docs/devices#tempo-sync). | | Note | 1/32 triplet, 1/32, 1/32 dotted, 1/16 triplet, 1/16, 1/16 dotted, 1/8 triplet, 1/8, 1/8 dotted, 1/4 triplet, 1/4, 1/4 dotted, 1/2 triplet, 1/2, 1/2 dotted, 1/1 triplet, 1/1, 1/1 dotted | 1/4 | The note value of one cycle of the oscillator. | | Depth | 0 % to 100 % | 60 % | How far the oscillator moves the pan or the level. | ## Panel The panel draws the movement over two seconds. `autoPanWave(shape, phase)` is the wave and `autoPanSweep(state)` is what the panel draws. ```tsx import { AutoPanPanel } from "@/components/audio-ui/devices/auto-pan/panel"; import { autoPanDevice } from "@/components/audio-ui/devices/auto-pan/device"; const [state, setState] = useState(() => autoPanDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). One oscillator feeds both a stereo panner and a gain, and the mode sets which of the two depths is on. In Tremolo mode the level swings around the middle of its range, so a depth of 100 % goes from silence to full level. --- # Channel EQ > A channel EQ device: a low shelf, a sweepable mid bell, a high shelf, a high-pass switch and an output level, a panel with a handle on the mid band, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { ChannelEqPanel } from "@/components/audio-ui/devices/channel-eq/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { useSpectrum } from "@/hooks/use-spectrum"; import { type ChannelEqState, channelEqDevice, } from "@/components/audio-ui/devices/channel-eq/device"; import { createChannelEqEngine } from "@/components/audio-ui/devices/channel-eq/engine"; const MASTER_VOLUME = 0.7; const MIN_HZ = 20; const MAX_HZ = 20_000; /** * A channel EQ you can plug in: its state, a panel that draws the curve it * plays with a handle on the mid band and an engine that plays it, each its * own file and none knowing the others. Play the loop and drag the handle: the * spectrum behind is what comes out. */ export function BlockChannelEq() { const [state, setState] = useState(() => channelEqDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { analyser } = useDeviceLoop({ create: createChannelEqEngine, destination: master, state, }); const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); return (
); } ``` The EQ of a mixer strip, simpler than the [equalizer](/docs/components/base/equalizer): a low shelf, a mid bell you sweep, a high shelf and a high-pass for the rumble. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/channel-eq ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/channel-eq/`. The demo above, which wires them to a loop, is `@audio-ui/block-channel-eq`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/channel-eq-device @audio-ui/channel-eq-panel @audio-ui/channel-eq-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-channel-eq.tsx" "use client"; import { useState } from "react"; import { ChannelEqPanel } from "@/components/audio-ui/devices/channel-eq/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { useSpectrum } from "@/hooks/use-spectrum"; import { type ChannelEqState, channelEqDevice, } from "@/components/audio-ui/devices/channel-eq/device"; import { createChannelEqEngine } from "@/components/audio-ui/devices/channel-eq/engine"; const MASTER_VOLUME = 0.7; const MIN_HZ = 20; const MAX_HZ = 20_000; /** * A channel EQ you can plug in: its state, a panel that draws the curve it * plays with a handle on the mid band and an engine that plays it, each its * own file and none knowing the others. Play the loop and drag the handle: the * spectrum behind is what comes out. */ export function BlockChannelEq() { const [state, setState] = useState(() => channelEqDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { analyser } = useDeviceLoop({ create: createChannelEqEngine, destination: master, state, }); const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the channel eq from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | HP 80 Hz | On or off | Off | Cuts everything under 80 Hz. | | Low | -15 dB to 15 dB | 0 dB | The gain of the low shelf, at 100 Hz. | | Mid freq | 120 Hz to 7.5 kHz | 1 kHz | The centre of the mid bell. Drag the handle on the curve across to set it. | | Mid | -12 dB to 12 dB | 0 dB | The gain of the mid bell. Drag the handle up or down to set it. | | High | -15 dB to 15 dB | 0 dB | The gain of the high shelf, at 6 kHz. | | Output | -12 dB to 12 dB | 0 dB | The level of the output. | ## Panel The panel draws the curve of the four filters and the output level, with a handle on the mid band. ```tsx import { ChannelEqPanel } from "@/components/audio-ui/devices/channel-eq/panel"; import { channelEqDevice } from "@/components/audio-ui/devices/channel-eq/device"; const [state, setState] = useState(() => channelEqDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). Four filters in series and an output gain, the same the curve draws. With the high-pass off, it is a 10 Hz high-pass, which passes the whole spectrum, so the curve and the sound agree. `channelEqBands(state)` gives the filters. --- # Chorus > A chorus device: a rate or a note value, a depth, a delay and a mix, a panel that draws the sweep of the delay, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { ChorusPanel } from "@/components/audio-ui/devices/chorus/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type ChorusState, chorusDevice, } from "@/components/audio-ui/devices/chorus/device"; import { createChorusEngine } from "@/components/audio-ui/devices/chorus/engine"; const MASTER_VOLUME = 0.7; /** * A chorus you can plug in: its state, a panel that draws the sweep of its * delay and an engine that plays it, each its own file and none knowing the * others. Play the loop and turn the rate and the depth. */ export function BlockChorus() { const [state, setState] = useState(() => chorusDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { tempo } = useDeviceLoop({ create: createChorusEngine, destination: master, state, }); return (
); } ``` Thickens the sound with a short delay that a slow oscillator sweeps up and down. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/chorus ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/chorus/`. The demo above, which wires them to a loop, is `@audio-ui/block-chorus`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/chorus-device @audio-ui/chorus-panel @audio-ui/chorus-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-chorus.tsx" "use client"; import { useState } from "react"; import { ChorusPanel } from "@/components/audio-ui/devices/chorus/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type ChorusState, chorusDevice, } from "@/components/audio-ui/devices/chorus/device"; import { createChorusEngine } from "@/components/audio-ui/devices/chorus/engine"; const MASTER_VOLUME = 0.7; /** * A chorus you can plug in: its state, a panel that draws the sweep of its * delay and an engine that plays it, each its own file and none knowing the * others. Play the loop and turn the rate and the depth. */ export function BlockChorus() { const [state, setState] = useState(() => chorusDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { tempo } = useDeviceLoop({ create: createChorusEngine, destination: master, state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the chorus from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Rate | 0.05 Hz to 8.00 Hz | 0.80 Hz | How fast the oscillator sweeps the delay. | | Sync | On or off | Off | Takes the rate from a note value and the tempo of the host. See [Tempo sync](/docs/devices#tempo-sync). | | Note | 1/32 triplet, 1/32, 1/32 dotted, 1/16 triplet, 1/16, 1/16 dotted, 1/8 triplet, 1/8, 1/8 dotted, 1/4 triplet, 1/4, 1/4 dotted, 1/2 triplet, 1/2, 1/2 dotted, 1/1 triplet, 1/1, 1/1 dotted | 1/4 | The note value of one cycle of the oscillator. | | Depth | 0 % to 100 % | 40 % | How far the oscillator moves the delay. | | Delay | 5 ms to 40 ms | 18 ms | The delay the sweep is centred on. | | Mix | 0 % to 100 % | 50 % | The balance of the delayed signal and the dry one. | ## Panel The panel draws the delay time over two seconds as the oscillator moves it. `chorusSweep(state)` is what it draws. With Sync on, it draws the oscillator at the rate it really has. ```tsx import { ChorusPanel } from "@/components/audio-ui/devices/chorus/panel"; import { chorusDevice } from "@/components/audio-ui/devices/chorus/device"; const [state, setState] = useState(() => chorusDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). The output of the oscillator, scaled by the depth, is added to the delay time. The sweep is kept inside the delay, so the time never goes negative. --- # Compressor > A compressor device: threshold, ratio, attack, release, knee, make-up and mix, a panel that draws its transfer curve, a Web Audio engine with a sidechain, and tools for agents. ```tsx "use client"; import { createSource } from "@audio-ui/react"; import { useEffect, useRef, useState } from "react"; import { CompressorPanel } from "@/components/audio-ui/devices/compressor/panel"; import { useDemoSource } from "@/hooks/use-demo-source"; import { useMasterBus } from "@/hooks/use-master-bus"; import { usePlaySwitch } from "@/hooks/use-play-switch"; import { type CompressorState, compressorDevice, } from "@/components/audio-ui/devices/compressor/device"; import { type CompressorEngine, createCompressorEngine, } from "@/components/audio-ui/devices/compressor/engine"; import { demoKey, renderDemoSource, } from "@/lib/demo-sound"; import { webAudio } from "@/lib/web-audio"; const FLOOR_DB = -80; const FFT_SIZE = 1024; /** How fast the level falls back between pulses, in dB per frame. */ const LEVEL_FALL_DB = 1.2; const MASTER_VOLUME = 0.7; /** * A compressor you can plug in: its state, a panel that draws it, an engine * that plays it, side by side. Each is its own file and none knows the others: * the state is a plain object, so a host keeps its own and uses what it needs. * Play it from its session and turn the knobs; switch Sidechain on and a kick ducks a held chord. */ export function BlockCompressor() { const [state, setState] = useState(() => compressorDevice.defaults() ); const { playing } = usePlaySwitch(); const master = useMasterBus(MASTER_VOLUME); const [level] = useState(() => createSource(FLOOR_DB)); const engine = useRef(null); const stateRef = useRef(state); stateRef.current = state; // With the key on, a held chord is ducked by the kick of a loop: the key is heard by the compressor only. const keyed = state.external; const name = useDemoSource(keyed ? "chord" : "groove"); useEffect(() => { const ctx = webAudio.getContext(); if (!(playing && ctx && master)) { return; } ctx.resume(); let cancelled = false; let stop = () => undefined; const buffers = Promise.all([ renderDemoSource(name, ctx.sampleRate), keyed ? renderDemoSource(demoKey(name), ctx.sampleRate) : null, ]); buffers.then(([signal, key]) => { if (cancelled) { return; } const source = ctx.createBufferSource(); source.buffer = signal; source.loop = true; const keySource = key ? ctx.createBufferSource() : null; const compressor = createCompressorEngine(ctx, stateRef.current); const tap = ctx.createAnalyser(); tap.fftSize = FFT_SIZE; source.connect(tap); source.connect(compressor.input); if (keySource && key) { keySource.buffer = key; keySource.loop = true; keySource.connect(compressor.sidechain); } compressor.output.connect(master); engine.current = compressor; const startAt = ctx.currentTime + 0.05; source.start(startAt); keySource?.start(startAt); const samples = new Float32Array(new ArrayBuffer(tap.fftSize * 4)); let held = FLOOR_DB; let frame = 0; const tick = () => { tap.getFloatTimeDomainData(samples); let peak = 0; for (const sample of samples) { peak = Math.max(peak, Math.abs(sample)); } const db = peak > 0 ? Math.max(FLOOR_DB, 20 * Math.log10(peak)) : FLOOR_DB; held = Math.max(db, held - LEVEL_FALL_DB); level.set(held); frame = requestAnimationFrame(tick); }; frame = requestAnimationFrame(tick); stop = () => { cancelAnimationFrame(frame); source.stop(); source.disconnect(); keySource?.stop(); keySource?.disconnect(); tap.disconnect(); compressor.dispose(); engine.current = null; level.set(FLOOR_DB); }; }); return () => { cancelled = true; stop(); }; }, [keyed, level, master, name, playing]); // The engine follows the state, whoever changed it: a knob or a call. useEffect(() => { engine.current?.update(state); }, [state]); return (
); } ``` Brings loud parts down. Above the threshold, the level rises by one decibel for every `ratio` decibels in. With the sidechain on, it follows the level of another signal, so a kick can duck a pad. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/compressor ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/compressor/`. The demo above, which wires them to a loop, is `@audio-ui/block-compressor`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/compressor-device @audio-ui/compressor-panel @audio-ui/compressor-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-compressor.tsx" "use client"; import { createSource } from "@audio-ui/react"; import { useEffect, useRef, useState } from "react"; import { CompressorPanel } from "@/components/audio-ui/devices/compressor/panel"; import { useDemoSource } from "@/hooks/use-demo-source"; import { useMasterBus } from "@/hooks/use-master-bus"; import { usePlaySwitch } from "@/hooks/use-play-switch"; import { type CompressorState, compressorDevice, } from "@/components/audio-ui/devices/compressor/device"; import { type CompressorEngine, createCompressorEngine, } from "@/components/audio-ui/devices/compressor/engine"; import { demoKey, renderDemoSource, } from "@/lib/demo-sound"; import { webAudio } from "@/lib/web-audio"; const FLOOR_DB = -80; const FFT_SIZE = 1024; /** How fast the level falls back between pulses, in dB per frame. */ const LEVEL_FALL_DB = 1.2; const MASTER_VOLUME = 0.7; /** * A compressor you can plug in: its state, a panel that draws it, an engine * that plays it, side by side. Each is its own file and none knows the others: * the state is a plain object, so a host keeps its own and uses what it needs. * Play it from its session and turn the knobs; switch Sidechain on and a kick ducks a held chord. */ export function BlockCompressor() { const [state, setState] = useState(() => compressorDevice.defaults() ); const { playing } = usePlaySwitch(); const master = useMasterBus(MASTER_VOLUME); const [level] = useState(() => createSource(FLOOR_DB)); const engine = useRef(null); const stateRef = useRef(state); stateRef.current = state; // With the key on, a held chord is ducked by the kick of a loop: the key is heard by the compressor only. const keyed = state.external; const name = useDemoSource(keyed ? "chord" : "groove"); useEffect(() => { const ctx = webAudio.getContext(); if (!(playing && ctx && master)) { return; } ctx.resume(); let cancelled = false; let stop = () => undefined; const buffers = Promise.all([ renderDemoSource(name, ctx.sampleRate), keyed ? renderDemoSource(demoKey(name), ctx.sampleRate) : null, ]); buffers.then(([signal, key]) => { if (cancelled) { return; } const source = ctx.createBufferSource(); source.buffer = signal; source.loop = true; const keySource = key ? ctx.createBufferSource() : null; const compressor = createCompressorEngine(ctx, stateRef.current); const tap = ctx.createAnalyser(); tap.fftSize = FFT_SIZE; source.connect(tap); source.connect(compressor.input); if (keySource && key) { keySource.buffer = key; keySource.loop = true; keySource.connect(compressor.sidechain); } compressor.output.connect(master); engine.current = compressor; const startAt = ctx.currentTime + 0.05; source.start(startAt); keySource?.start(startAt); const samples = new Float32Array(new ArrayBuffer(tap.fftSize * 4)); let held = FLOOR_DB; let frame = 0; const tick = () => { tap.getFloatTimeDomainData(samples); let peak = 0; for (const sample of samples) { peak = Math.max(peak, Math.abs(sample)); } const db = peak > 0 ? Math.max(FLOOR_DB, 20 * Math.log10(peak)) : FLOOR_DB; held = Math.max(db, held - LEVEL_FALL_DB); level.set(held); frame = requestAnimationFrame(tick); }; frame = requestAnimationFrame(tick); stop = () => { cancelAnimationFrame(frame); source.stop(); source.disconnect(); keySource?.stop(); keySource?.disconnect(); tap.disconnect(); compressor.dispose(); engine.current = null; level.set(FLOOR_DB); }; }); return () => { cancelled = true; stop(); }; }, [keyed, level, master, name, playing]); // The engine follows the state, whoever changed it: a knob or a call. useEffect(() => { engine.current?.update(state); }, [state]); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the compressor from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Threshold | -60 dB to 0 dB | -18 dB | The level above which the compressor works. | | Ratio | 1:1 to 20:1 | 4:1 | How much the level is brought down above the threshold. At 4:1, 4 dB in give 1 dB out. | | Attack | 0.1 ms to 100 ms | 5 ms | How fast the compressor takes the gain down once the level is over the threshold. | | Release | 10 ms to 1000 ms | 80 ms | How fast the gain comes back once the level is under it. | | Knee | 0 dB to 40 dB | 6 dB | How gradually the compressor starts to work around the threshold. 0 is a hard knee. | | Auto make-up | On or off | On | Keeps the make-up gain the browser's node adds on its own, which grows with the threshold and the ratio. | | Make-up | 0 dB to 24 dB | 0 dB | Makes up for the gain taken off. It does nothing while Auto make-up is on. | | Mix | 0 % to 100 % | 100 % | The balance of the compressed signal and the dry one, for parallel compression. | | Sidechain | On or off | Off | Makes the compressor follow the signal connected to `engine.sidechain`. See [Sidechain](/docs/devices#sidechain). | ## Panel The panel draws the transfer curve the state plays: the threshold, the dashed unity line, and a dot that rides the curve at the level going in. Pass `level`, a live source in dB, to show the dot. Below the threshold the curve sits above unity by the make-up gain. ```tsx import { CompressorPanel } from "@/components/audio-ui/devices/compressor/panel"; import { compressorDevice } from "@/components/audio-ui/devices/compressor/device"; const [state, setState] = useState(() => compressorDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). ```ts engine.reduction; // dB being taken off, read per frame ``` What goes on each node comes from `compressorSettings(state)`. Two things the browser's compressor node does that the engine accounts for: - **It adds a make-up gain of its own that cannot be turned off.** It grows with the threshold and the ratio (+10.8 dB at -24 dB and 4:1). With Auto make-up off, the engine takes it back out and applies Make-up. With it on, the node's is kept. - **It looks ahead by 6 ms.** The dry path waits as long, so a parallel mix does not comb. This is the [latency](/docs/devices#latency) of the device. With the sidechain on, the browser's node has no input for it, so the signal goes through a gain that a worklet drives. The worklet follows the peak of the sidechain, instant up and 10 ms down, and applies the same curve as the node, with a soft knee, a slope of 1/ratio over the threshold, and the attack and release on the reduction. The make-up of the node is added by hand. Measured in Chrome with a sine at -6 dB over a threshold of -18 dB at 4:1, it takes off 8.9 dB at 1 kHz and 8.5 dB at 60 Hz, where the curve says 9. With the sidechain on, `engine.reduction` reads the detector. ## How close the curve is The curve is the static curve of the node: the level once the gain has settled. A real detector follows a signal with an attack and a release, so what you hear sits a little above it. Measured in Chrome with a 440 Hz sine, it is about 0.5 dB at the defaults and up to 1.3 dB with a slow attack and a short release. Below the threshold it is exact. --- # De-esser > A de-esser device: frequency, threshold, ratio, range and listen, a panel that draws what it does at each frequency, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { DeesserPanel } from "@/components/audio-ui/devices/deesser/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { useSpectrum } from "@/hooks/use-spectrum"; import { type DeesserState, deesserDevice, } from "@/components/audio-ui/devices/deesser/device"; import { createDeesserEngine } from "@/components/audio-ui/devices/deesser/engine"; const MASTER_VOLUME = 0.7; const MIN_HZ = 500; const MAX_HZ = 20_000; /** * A de-esser you can plug in: its state, a panel that draws what it does at * each frequency and an engine that plays it, each its own file and none * knowing the others. It plays a loop: lower * the threshold and the highs sit back, switch Listen on to hear the highs alone. */ export function BlockDeesser() { const [state, setState] = useState(() => deesserDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { analyser } = useDeviceLoop({ create: createDeesserEngine, destination: master, source: "groove", state, }); const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); return (
); } ``` Softens the sharp s and t of a voice. The signal is split at a frequency, and when the highs above it go over the threshold they are taken down, never by more than the range. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/deesser ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/deesser/`. The demo above, which wires them to a loop, is `@audio-ui/block-deesser`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/deesser-device @audio-ui/deesser-panel @audio-ui/deesser-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-deesser.tsx" "use client"; import { useState } from "react"; import { DeesserPanel } from "@/components/audio-ui/devices/deesser/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { useSpectrum } from "@/hooks/use-spectrum"; import { type DeesserState, deesserDevice, } from "@/components/audio-ui/devices/deesser/device"; import { createDeesserEngine } from "@/components/audio-ui/devices/deesser/engine"; const MASTER_VOLUME = 0.7; const MIN_HZ = 500; const MAX_HZ = 20_000; /** * A de-esser you can plug in: its state, a panel that draws what it does at * each frequency and an engine that plays it, each its own file and none * knowing the others. It plays a loop: lower * the threshold and the highs sit back, switch Listen on to hear the highs alone. */ export function BlockDeesser() { const [state, setState] = useState(() => deesserDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { analyser } = useDeviceLoop({ create: createDeesserEngine, destination: master, source: "groove", state, }); const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the deesser from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Frequency | 2 kHz to 12 kHz | 6.5 kHz | Where the highs start. Drag the handle on the plot across to set it. | | Threshold | -60 dB to 0 dB | -32 dB | The level of the highs above which they are taken down. | | Ratio | 1:1 to 20:1 | 6:1 | How much the highs are brought down above the threshold. | | Range | 0 dB to 24 dB | 12 dB | The most the highs are taken down. Drag the handle down to raise it. | | Listen | On or off | Off | Plays only the highs, to find where the sibilants sit. | ## Panel The panel draws what the device does at each frequency at full reduction. The handle sits on the curve at the frequency: drag it across for the frequency and down for the range. `deesserResponse(state)` is the curve the panel draws. Pass a spectrum to the panel to see what comes out behind the curve. ```tsx import { DeesserPanel } from "@/components/audio-ui/devices/deesser/panel"; import { deesserDevice } from "@/components/audio-ui/devices/deesser/device"; const [state, setState] = useState(() => deesserDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). ```ts engine.reduction; // dB taken off the highs, read per frame ``` Two biquads in a row make each half of a Linkwitz-Riley split, whose low and high halves add back to a flat response when nothing is taken down. A detector reads the highs and writes the gain they get. It is the one of the compressor's [sidechain](/docs/devices#sidechain), with a soft knee of 3 dB, an attack of 0.5 ms and a release of 60 ms. A table keeps the gain from going under the range. Measured in Chrome, with nothing over the threshold the output is within 0.01 dB of the input from 200 Hz to 12 kHz. At full reduction a 10 kHz tone goes down by 5.1, 9.6 and 15.7 dB for ranges of 6, 12 and 24 dB, which is the curve the panel draws, to the hundredth. --- # Delay > A delay device: a time or a note value, a feedback, a tone and a mix, a panel that draws the echoes with a handle, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { DelayPanel } from "@/components/audio-ui/devices/delay/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type DelayState, delayDevice, } from "@/components/audio-ui/devices/delay/device"; import { createDelayEngine } from "@/components/audio-ui/devices/delay/engine"; const MASTER_VOLUME = 0.7; /** A dotted eighth: the echo that has made a thousand guitars sound larger. */ const START = { division: "1/8d", sync: true }; /** * A delay you can plug in: its state, a panel that draws the echoes it makes * and an engine that plays it, each its own file and none knowing the others. * Play the loop and drag the handle: across for the time, up for the feedback. * It starts synced to the loop's tempo, on a dotted eighth. */ export function BlockDelay() { const [state, setState] = useState( () => delayDevice.apply(delayDevice.defaults(), START).state ); const master = useMasterBus(MASTER_VOLUME); const { tempo } = useDeviceLoop({ create: createDelayEngine, destination: master, state, }); return (
); } ``` Repeats the sound. The echoes fade by the feedback, each darker than the one before. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/delay ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/delay/`. The demo above, which wires them to a loop, is `@audio-ui/block-delay`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/delay-device @audio-ui/delay-panel @audio-ui/delay-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-delay.tsx" "use client"; import { useState } from "react"; import { DelayPanel } from "@/components/audio-ui/devices/delay/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type DelayState, delayDevice, } from "@/components/audio-ui/devices/delay/device"; import { createDelayEngine } from "@/components/audio-ui/devices/delay/engine"; const MASTER_VOLUME = 0.7; /** A dotted eighth: the echo that has made a thousand guitars sound larger. */ const START = { division: "1/8d", sync: true }; /** * A delay you can plug in: its state, a panel that draws the echoes it makes * and an engine that plays it, each its own file and none knowing the others. * Play the loop and drag the handle: across for the time, up for the feedback. * It starts synced to the loop's tempo, on a dotted eighth. */ export function BlockDelay() { const [state, setState] = useState( () => delayDevice.apply(delayDevice.defaults(), START).state ); const master = useMasterBus(MASTER_VOLUME); const { tempo } = useDeviceLoop({ create: createDelayEngine, destination: master, state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the delay from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Time | 10 ms to 2000 ms | 350 ms | The time between the echoes. Drag the handle on the first echo across to set it. | | Sync | On or off | Off | Takes the time from a note value and the tempo of the host instead of milliseconds. See [Tempo sync](/docs/devices#tempo-sync). | | Note | 1/32 triplet, 1/32, 1/32 dotted, 1/16 triplet, 1/16, 1/16 dotted, 1/8 triplet, 1/8, 1/8 dotted, 1/4 triplet, 1/4, 1/4 dotted, 1/2 triplet, 1/2, 1/2 dotted, 1/1 triplet, 1/1, 1/1 dotted | 1/8 | The note value of the time, from 1/32 to a whole note, with triplets and dotted notes. | | Feedback | 0 % to 95 % | 40 % | How much of the output goes back in. Drag the handle on the first echo up to raise it. | | Tone | 200 Hz to 20 kHz | 6 kHz | Closes the highs of each repeat. | | Mix | 0 % to 100 % | 30 % | The balance of the echoes and the dry signal. | ## Panel The panel draws the echoes the state makes, one line each, fainter as they fade. `delayTaps(state, windowMs)` returns them. With Sync on, the handle lands on the nearest note value and the Time control is drawn off. With Sync off, the note list is. ```tsx import { DelayPanel } from "@/components/audio-ui/devices/delay/panel"; import { delayDevice } from "@/components/audio-ui/devices/delay/device"; const [state, setState] = useState(() => delayDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). The repeats go round a low-pass filter, so each is darker than the one before. A change of time glides slowly, so the echo bends like a tape instead of clicking, and the feedback stops short of 95 % so it cannot run away. A note longer than the delay can hold (two seconds) is held to that. The `1/8d` the block starts on is a dotted eighth at the loop's 100 BPM, 450 ms. --- # Distortion > A distortion device: a drive, a tone, a mix and an output, a panel that draws the transfer curve, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { DistortionPanel } from "@/components/audio-ui/devices/distortion/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type DistortionState, distortionDevice, } from "@/components/audio-ui/devices/distortion/device"; import { createDistortionEngine } from "@/components/audio-ui/devices/distortion/engine"; const MASTER_VOLUME = 0.7; /** * A distortion you can plug in: its state, a panel that draws its transfer * curve and an engine that plays it, each its own file and none knowing the * others. Play the loop and turn the drive: the curve bends as the sound does. */ export function BlockDistortion() { const [state, setState] = useState(() => distortionDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createDistortionEngine, destination: master, state, }); return (
); } ``` Bends the sound. The more the drive, the more the peaks round off. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/distortion ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/distortion/`. The demo above, which wires them to a loop, is `@audio-ui/block-distortion`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/distortion-device @audio-ui/distortion-panel @audio-ui/distortion-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-distortion.tsx" "use client"; import { useState } from "react"; import { DistortionPanel } from "@/components/audio-ui/devices/distortion/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type DistortionState, distortionDevice, } from "@/components/audio-ui/devices/distortion/device"; import { createDistortionEngine } from "@/components/audio-ui/devices/distortion/engine"; const MASTER_VOLUME = 0.7; /** * A distortion you can plug in: its state, a panel that draws its transfer * curve and an engine that plays it, each its own file and none knowing the * others. Play the loop and turn the drive: the curve bends as the sound does. */ export function BlockDistortion() { const [state, setState] = useState(() => distortionDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createDistortionEngine, destination: master, state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the distortion from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Drive | 0 dB to 40 dB | 12 dB | How hard the signal is pushed into the clip. | | Tone | 500 Hz to 20 kHz | 6 kHz | Closes the highs after the clip. | | Mix | 0 % to 100 % | 100 % | The balance of the distorted signal and the clean one. | | Output | -24 dB to 12 dB | -6 dB | The level of the output. | ## Panel The panel draws the transfer curve, the output for each input, against the straight line of a clean sound. `softClip(input, drive)` is the clip and `distortionCurve(state)` is the whole curve with the mix and the output. ```tsx import { DistortionPanel } from "@/components/audio-ui/devices/distortion/panel"; import { distortionDevice } from "@/components/audio-ui/devices/distortion/device"; const [state, setState] = useState(() => distortionDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). The drive is a gain before one fixed soft-clip table, so turning it never rebuilds the table. The shaper oversamples 4x to keep the clip from aliasing, which is the [latency](/docs/devices#latency) of the device. --- # Equalizer > An equalizer device: four bands with a type, a frequency, a gain and a width, a panel with a handle on each band, a Web Audio engine and tools for agents. ```tsx "use client"; import { useEffect, useRef, useState } from "react"; import { EqualizerPanel } from "@/components/audio-ui/devices/equalizer/panel"; import { useDemoSource } from "@/hooks/use-demo-source"; import { useMasterBus } from "@/hooks/use-master-bus"; import { usePlaySwitch } from "@/hooks/use-play-switch"; import { useSpectrum } from "@/hooks/use-spectrum"; import { renderDemoSource } from "@/lib/demo-sound"; import { type EqualizerState, equalizerDevice, } from "@/components/audio-ui/devices/equalizer/device"; import { createEqualizerEngine, type EqualizerEngine, } from "@/components/audio-ui/devices/equalizer/engine"; import { webAudio } from "@/lib/web-audio"; const FFT_SIZE = 4096; const ANALYSER_SMOOTHING = 0.8; const MASTER_VOLUME = 0.7; const MIN_HZ = 20; const MAX_HZ = 20_000; /** A shape worth looking at: some weight, a dip in the low mids, some air. */ const START = { highDb: 5, lowDb: 3, lowMidDb: -4 }; /** * An equalizer you can plug in: its state, a panel that draws it and an engine * that plays it, each its own file and none knowing the others. A loop * plays through it while its session's play switch is on, and the spectrum * behind the curve is what comes out. */ export function BlockEqualizer() { const [state, setState] = useState( () => equalizerDevice.apply(equalizerDevice.defaults(), START).state ); const { playing } = usePlaySwitch(); const [analyser, setAnalyser] = useState(null); const master = useMasterBus(MASTER_VOLUME); const engine = useRef(null); const stateRef = useRef(state); stateRef.current = state; const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); const name = useDemoSource("groove"); useEffect(() => { const ctx = webAudio.getContext(); if (!(playing && ctx && master)) { return; } ctx.resume(); let cancelled = false; let stop = () => undefined; renderDemoSource(name, ctx.sampleRate).then((buffer) => { if (cancelled) { return; } const source = ctx.createBufferSource(); source.buffer = buffer; source.loop = true; const eq = createEqualizerEngine(ctx, stateRef.current); const tap = ctx.createAnalyser(); tap.fftSize = FFT_SIZE; tap.smoothingTimeConstant = ANALYSER_SMOOTHING; source.connect(eq.input); eq.output.connect(tap); eq.output.connect(master); engine.current = eq; source.start(); setAnalyser(tap); stop = () => { source.stop(); source.disconnect(); tap.disconnect(); eq.dispose(); engine.current = null; setAnalyser(null); }; }); return () => { cancelled = true; stop(); }; }, [master, name, playing]); // The engine follows the state, whoever changed it: a handle, a knob or a call. useEffect(() => { engine.current?.update(state); }, [state]); return (
); } ``` Shapes the spectrum with four bands in series, then an output level. The panel draws the filters the engine runs, so what you see is what you hear. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/equalizer ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/equalizer/`. The demo above, which wires them to a loop, is `@audio-ui/block-equalizer`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/equalizer-device @audio-ui/equalizer-panel @audio-ui/equalizer-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-equalizer.tsx" "use client"; import { useEffect, useRef, useState } from "react"; import { EqualizerPanel } from "@/components/audio-ui/devices/equalizer/panel"; import { useDemoSource } from "@/hooks/use-demo-source"; import { useMasterBus } from "@/hooks/use-master-bus"; import { usePlaySwitch } from "@/hooks/use-play-switch"; import { useSpectrum } from "@/hooks/use-spectrum"; import { renderDemoSource } from "@/lib/demo-sound"; import { type EqualizerState, equalizerDevice, } from "@/components/audio-ui/devices/equalizer/device"; import { createEqualizerEngine, type EqualizerEngine, } from "@/components/audio-ui/devices/equalizer/engine"; import { webAudio } from "@/lib/web-audio"; const FFT_SIZE = 4096; const ANALYSER_SMOOTHING = 0.8; const MASTER_VOLUME = 0.7; const MIN_HZ = 20; const MAX_HZ = 20_000; /** A shape worth looking at: some weight, a dip in the low mids, some air. */ const START = { highDb: 5, lowDb: 3, lowMidDb: -4 }; /** * An equalizer you can plug in: its state, a panel that draws it and an engine * that plays it, each its own file and none knowing the others. A loop * plays through it while its session's play switch is on, and the spectrum * behind the curve is what comes out. */ export function BlockEqualizer() { const [state, setState] = useState( () => equalizerDevice.apply(equalizerDevice.defaults(), START).state ); const { playing } = usePlaySwitch(); const [analyser, setAnalyser] = useState(null); const master = useMasterBus(MASTER_VOLUME); const engine = useRef(null); const stateRef = useRef(state); stateRef.current = state; const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); const name = useDemoSource("groove"); useEffect(() => { const ctx = webAudio.getContext(); if (!(playing && ctx && master)) { return; } ctx.resume(); let cancelled = false; let stop = () => undefined; renderDemoSource(name, ctx.sampleRate).then((buffer) => { if (cancelled) { return; } const source = ctx.createBufferSource(); source.buffer = buffer; source.loop = true; const eq = createEqualizerEngine(ctx, stateRef.current); const tap = ctx.createAnalyser(); tap.fftSize = FFT_SIZE; tap.smoothingTimeConstant = ANALYSER_SMOOTHING; source.connect(eq.input); eq.output.connect(tap); eq.output.connect(master); engine.current = eq; source.start(); setAnalyser(tap); stop = () => { source.stop(); source.disconnect(); tap.disconnect(); eq.dispose(); engine.current = null; setAnalyser(null); }; }); return () => { cancelled = true; stop(); }; }, [master, name, playing]); // The engine follows the state, whoever changed it: a handle, a knob or a call. useEffect(() => { engine.current?.update(state); }, [state]); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the equalizer from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Low type | Low cut, Low shelf, Bell, Notch, High shelf, High cut | Low shelf | The shape of the first band. A shelf by default. | | Low freq | 20 Hz to 500 Hz | 100 Hz | The frequency of the first band. | | Low gain | -18 dB to 18 dB | 0 dB | The gain of the first band. A cut or a notch has none. | | Low Q | 0.30 to 12.00 | 0.71 | The width of the first band. A shelf has a fixed slope and ignores it. | | Low mid type | Low cut, Low shelf, Bell, Notch, High shelf, High cut | Bell | The shape of the second band. A bell by default. | | Low mid freq | 100 Hz to 2 kHz | 400 Hz | The frequency of the second band. | | Low mid gain | -18 dB to 18 dB | 0 dB | The gain of the second band. | | Low mid Q | 0.30 to 12.00 | 1.00 | The width of the second band. | | High mid type | Low cut, Low shelf, Bell, Notch, High shelf, High cut | Bell | The shape of the third band. A bell by default. | | High mid freq | 800 Hz to 8 kHz | 2.5 kHz | The frequency of the third band. | | High mid gain | -18 dB to 18 dB | 0 dB | The gain of the third band. | | High mid Q | 0.30 to 12.00 | 1.00 | The width of the third band. | | High type | Low cut, Low shelf, Bell, Notch, High shelf, High cut | High shelf | The shape of the fourth band. A shelf by default. | | High freq | 2 kHz to 20 kHz | 8 kHz | The frequency of the fourth band. | | High gain | -18 dB to 18 dB | 0 dB | The gain of the fourth band. | | High Q | 0.30 to 12.00 | 0.71 | The width of the fourth band. | | Output | -12 dB to 12 dB | 0 dB | The level of the output. | ## Panel The curve is the sum of the four filters and the output level. Each band has a handle on it: drag it to set the frequency and the gain of the band, and it follows the pointer one to one. A cut or a notch has no gain, so its handle only slides. Double-click a handle to flatten the band. Pick a band by its number or its handle, and its type, frequency, gain and width appear under the curve, the unused ones drawn off. Pass a `spectrum` (from `useSpectrum`, see [Analysis](/docs/engine/analysis#spectrum)) to draw the level of the sound behind the curve. The type of a band decides what it uses: | Type | Gain | Width | | --- | --- | --- | | Low cut, high cut | No | Yes | | Notch | No | Yes | | Low shelf, high shelf | Yes | No | | Bell | Yes | Yes | The cuts are 12 dB per octave, which is what a browser filter node does. ```tsx import { EqualizerPanel } from "@/components/audio-ui/devices/equalizer/panel"; import { equalizerDevice } from "@/components/audio-ui/devices/equalizer/device"; const [state, setState] = useState(() => equalizerDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). Four `BiquadFilterNode`s in series and an output gain. The curve is drawn from the same formulas the node runs, and the width of a band goes through `toWebAudioQ` on the way to the node, so the two agree. Off, every band goes flat and the output goes to 0 dB. ## Measure your engine A host that brings its own engine can check it against what the panel draws. See [Measure your engine](/docs/devices#measure-your-engine): it works for the equalizer, the filter and the channel EQ. --- # Filter > A filter device: a type, a cutoff and a resonance, a panel with a handle on the curve and a live spectrum, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { FilterPanel } from "@/components/audio-ui/devices/filter/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { useSpectrum } from "@/hooks/use-spectrum"; import { type FilterState, filterDevice, } from "@/components/audio-ui/devices/filter/device"; import { createFilterEngine } from "@/components/audio-ui/devices/filter/engine"; const MASTER_VOLUME = 0.7; const MIN_HZ = 20; const MAX_HZ = 20_000; /** * A filter you can plug in: its state, a panel that draws the curve it plays * with a handle on the cutoff and an engine that plays it, each its own file * and none knowing the others. Play the loop and drag the handle: across for * the cutoff, up for the resonance; the spectrum behind is what comes out. */ export function BlockFilter() { const [state, setState] = useState(() => filterDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { analyser } = useDeviceLoop({ create: createFilterEngine, destination: master, state, }); const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); return (
); } ``` Takes part of the spectrum out: a low-pass, a high-pass, a band-pass or a notch. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/filter ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/filter/`. The demo above, which wires them to a loop, is `@audio-ui/block-filter`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/filter-device @audio-ui/filter-panel @audio-ui/filter-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-filter.tsx" "use client"; import { useState } from "react"; import { FilterPanel } from "@/components/audio-ui/devices/filter/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { useSpectrum } from "@/hooks/use-spectrum"; import { type FilterState, filterDevice, } from "@/components/audio-ui/devices/filter/device"; import { createFilterEngine } from "@/components/audio-ui/devices/filter/engine"; const MASTER_VOLUME = 0.7; const MIN_HZ = 20; const MAX_HZ = 20_000; /** * A filter you can plug in: its state, a panel that draws the curve it plays * with a handle on the cutoff and an engine that plays it, each its own file * and none knowing the others. Play the loop and drag the handle: across for * the cutoff, up for the resonance; the spectrum behind is what comes out. */ export function BlockFilter() { const [state, setState] = useState(() => filterDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { analyser } = useDeviceLoop({ create: createFilterEngine, destination: master, state, }); const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the filter from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Type | Low-pass, High-pass, Band-pass, Notch | Low-pass | The shape of the filter. | | Cutoff | 20 Hz to 20 kHz | 1.2 kHz | The frequency where the filter starts to work. Drag the handle across to set it. | | Resonance | 0.30 to 18.00 | 0.71 | How much the filter rings around the cutoff. Drag the handle up to raise it. | ## Panel The panel draws the curve of the filter, with a handle on it. Pass a spectrum to the panel to see what comes out behind the curve. `filterCurve(state)` is the curve it draws. ```tsx import { FilterPanel } from "@/components/audio-ui/devices/filter/panel"; import { filterDevice } from "@/components/audio-ui/devices/filter/device"; const [state, setState] = useState(() => filterDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). The node is the filter the curve draws. A low-pass and a high-pass read their resonance in decibels, so the device gives it to the node in that unit, and the curve and the sound agree. `filterSettings(state)` is what goes on the node. --- # Gate > A gate device: threshold, floor, attack, hold, release and look-ahead, a panel that draws its transfer curve, a Web Audio engine with a sidechain, and tools for agents. ```tsx "use client"; import { useState } from "react"; import { GatePanel } from "@/components/audio-ui/devices/gate/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type GateState, gateDevice, } from "@/components/audio-ui/devices/gate/device"; import { createGateEngine } from "@/components/audio-ui/devices/gate/engine"; const MASTER_VOLUME = 0.7; /** A held chord, opened by the kick of the loop: the key is heard by the gate only. */ const START = { external: true, floorDb: -70, attackMs: 1, holdMs: 20, releaseMs: 80, thresholdDb: -24, }; /** * A gate you can plug in: its state, a panel that draws its transfer curve * with a handle on the threshold and an engine that plays it, each its own * file. It starts keyed: a held chord that the kick of the loop opens and * closes. Raise the threshold and the kick opens it for less time; switch the * key off and the gate follows the chord itself. */ export function BlockGate() { const [state, setState] = useState( () => gateDevice.apply(gateDevice.defaults(), START).state ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createGateEngine, destination: master, key: true, source: "chord", state, }); return (
); } ``` Cuts the sound between hits. Above the threshold the signal passes, and below it the signal is turned down to the floor. With the sidechain on, a kick can open a held chord. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/gate ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/gate/`. The demo above, which wires them to a loop, is `@audio-ui/block-gate`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/gate-device @audio-ui/gate-panel @audio-ui/gate-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-gate.tsx" "use client"; import { useState } from "react"; import { GatePanel } from "@/components/audio-ui/devices/gate/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type GateState, gateDevice, } from "@/components/audio-ui/devices/gate/device"; import { createGateEngine } from "@/components/audio-ui/devices/gate/engine"; const MASTER_VOLUME = 0.7; /** A held chord, opened by the kick of the loop: the key is heard by the gate only. */ const START = { external: true, floorDb: -70, attackMs: 1, holdMs: 20, releaseMs: 80, thresholdDb: -24, }; /** * A gate you can plug in: its state, a panel that draws its transfer curve * with a handle on the threshold and an engine that plays it, each its own * file. It starts keyed: a held chord that the kick of the loop opens and * closes. Raise the threshold and the kick opens it for less time; switch the * key off and the gate follows the chord itself. */ export function BlockGate() { const [state, setState] = useState( () => gateDevice.apply(gateDevice.defaults(), START).state ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createGateEngine, destination: master, key: true, source: "chord", state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the gate from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Threshold | -70 dB to 0 dB | -36 dB | The level above which the gate opens. Drag the handle on the plot across to set it. | | Floor | -80 dB to 0 dB | -60 dB | How far the signal is turned down while the gate is closed. | | Attack | 0.1 ms to 50 ms | 1 ms | How fast the gate opens. | | Hold | 0 ms to 500 ms | 30 ms | How long the gate stays open after the level drops under the threshold. | | Release | 5 ms to 2000 ms | 120 ms | How fast the gate closes after the hold. | | Look-ahead | 0 ms to 10 ms | 0 ms | Delays the signal so the gate is open before a transient arrives. It adds the same [latency](/docs/devices#latency). | | Sidechain | On or off | Off | Makes the gate follow the signal connected to `engine.sidechain`. See [Sidechain](/docs/devices#sidechain). | ## Panel The panel draws the transfer curve against the straight line of a clean sound, with a handle on the threshold. With the sidechain on, the curve is not drawn, because what the gate does depends on the other signal. The plot then keeps the threshold, which is a level of the sidechain. ```tsx import { GatePanel } from "@/components/audio-ui/devices/gate/panel"; import { gateDevice } from "@/components/audio-ui/devices/gate/device"; const [state, setState] = useState(() => gateDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). The browser has no gate node, so the engine measures the level with an `AudioWorklet` that writes the gain to apply. The level is a peak follower. The gate is open while the level is over the threshold and for the hold after it, and the gain moves toward 1 or the floor with the attack or the release as a time constant. A delay in front of the gain is the look-ahead. The detector reads the signal before it, so the gate is open when a transient arrives. `gateSettings(state)` gives the numbers the engine puts on its nodes. Measured in Chrome, a hold of 100 ms keeps a quiet tone open for the 100 ms after a burst and then closes it to the floor, and 5 ms of look-ahead lets the first millisecond of a burst through at 0.50 instead of 0.26. --- # Limiter > A limiter device: input gain, ceiling and release, a panel that draws its transfer curve with a handle on the ceiling, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { LimiterPanel } from "@/components/audio-ui/devices/limiter/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type LimiterState, limiterDevice, } from "@/components/audio-ui/devices/limiter/device"; import { createLimiterEngine } from "@/components/audio-ui/devices/limiter/engine"; const MASTER_VOLUME = 0.7; /** * A limiter you can plug in: its state, a panel that draws its transfer curve with a handle on the ceiling and an engine that plays it, each its own file. Play the loop, push the gain and pull the ceiling down. */ export function BlockLimiter() { const [state, setState] = useState(() => limiterDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createLimiterEngine, destination: master, state, }); return (
); } ``` Keeps the sound under a ceiling. The input gain pushes the level against it, and what goes over is held down. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/limiter ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/limiter/`. The demo above, which wires them to a loop, is `@audio-ui/block-limiter`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/limiter-device @audio-ui/limiter-panel @audio-ui/limiter-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-limiter.tsx" "use client"; import { useState } from "react"; import { LimiterPanel } from "@/components/audio-ui/devices/limiter/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type LimiterState, limiterDevice, } from "@/components/audio-ui/devices/limiter/device"; import { createLimiterEngine } from "@/components/audio-ui/devices/limiter/engine"; const MASTER_VOLUME = 0.7; /** * A limiter you can plug in: its state, a panel that draws its transfer curve with a handle on the ceiling and an engine that plays it, each its own file. Play the loop, push the gain and pull the ceiling down. */ export function BlockLimiter() { const [state, setState] = useState(() => limiterDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createLimiterEngine, destination: master, state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the limiter from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Gain | 0 dB to 24 dB | 0 dB | Pushes the level of the input against the ceiling. | | Ceiling | -24 dB to 0 dB | -1 dB | The level the output should not go over. | | Release | 10 ms to 1000 ms | 100 ms | How fast the gain comes back after a peak. | ## Panel The panel draws the transfer curve against the straight line of a clean sound. Drag the handle up and down for the ceiling and across for the input gain. ```tsx import { LimiterPanel } from "@/components/audio-ui/devices/limiter/panel"; import { limiterDevice } from "@/components/audio-ui/devices/limiter/device"; const [state, setState] = useState(() => limiterDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). ```ts engine.reduction; // dB being taken off, read per frame ``` The engine is the browser's compressor node at a ratio of 20 with no knee, then a hard clip. The node adds a make-up gain of its own that cannot be turned off, so the engine takes it back out, and a signal under the ceiling is only as loud as the gain makes it. A ratio of 20 is not a wall. Measured in Chrome, with a ceiling of -1 dB and +24 dB in, the node alone reaches +0.6 dBFS. The final clip, oversampled 4x, keeps the samples at the ceiling: in the conformance page the peak is never more than 0.05 dB over it, for ceilings of -1, -6 and -12 dB and up to +36 dB in. The filter of the oversampling rings a little, so it is not exactly zero. That is a sample peak, not an inter-sample (true) peak. It is not a substitute for a true-peak limiter on a master that is checked against a loudness standard. --- # Mid/side > A mid/side device: a level for the centre, a level for the sides and a bass mono frequency, a panel with one handle for the two levels, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { MidSidePanel } from "@/components/audio-ui/devices/mid-side/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type MidSideState, midSideDevice, } from "@/components/audio-ui/devices/mid-side/device"; import { createMidSideEngine } from "@/components/audio-ui/devices/mid-side/engine"; const MASTER_VOLUME = 0.7; /** * A mid/side device you can plug in: its state, a panel with a handle for the * mid and the side and an engine that plays it, each its own file and none * knowing the others. It plays a loop: take the side down and the image closes in on the * centre, turn Bass mono up and the low end leaves the sides. */ export function BlockMidSide() { const [state, setState] = useState(() => midSideDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createMidSideEngine, destination: master, source: "groove", state, }); return (
); } ``` Sets the centre and the sides of a stereo signal apart. The mid is what both channels share, such as a kick or a voice, and the side is what sets them apart, such as a wide pad. Each has its own level, and Bass mono takes the lows out of the side so everything under a frequency sits in the middle. For a gain, a pan or a single width control, use the [utility](/docs/components/base/utility). It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/mid-side ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/mid-side/`. The demo above, which wires them to a loop, is `@audio-ui/block-mid-side`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/mid-side-device @audio-ui/mid-side-panel @audio-ui/mid-side-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-mid-side.tsx" "use client"; import { useState } from "react"; import { MidSidePanel } from "@/components/audio-ui/devices/mid-side/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type MidSideState, midSideDevice, } from "@/components/audio-ui/devices/mid-side/device"; import { createMidSideEngine } from "@/components/audio-ui/devices/mid-side/engine"; const MASTER_VOLUME = 0.7; /** * A mid/side device you can plug in: its state, a panel with a handle for the * mid and the side and an engine that plays it, each its own file and none * knowing the others. It plays a loop: take the side down and the image closes in on the * centre, turn Bass mono up and the low end leaves the sides. */ export function BlockMidSide() { const [state, setState] = useState(() => midSideDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createMidSideEngine, destination: master, source: "groove", state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the mid side from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Mid | -24 dB to 12 dB | 0 dB | The level of the centre. Drag the handle on the plot up or down to set it. | | Side | -24 dB to 12 dB | 0 dB | The level of the sides. Drag the handle on the plot across to set it. | | Bass mono | Off to 500 Hz | Off | The frequency under which the sides are taken out, so the bass sits in the centre. Off at 0. | ## Panel The panel is a square with the side level across and the mid level up, and one handle to drag to both at once. The crossing of the two lines is a signal left as it is. ```tsx import { MidSidePanel } from "@/components/audio-ui/devices/mid-side/panel"; import { midSideDevice } from "@/components/audio-ui/devices/mid-side/device"; const [state, setState] = useState(() => midSideDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). The signal is split into mid, `(L + R) / 2`, and side, `(L - R) / 2`. Each has its own gain, and the output is `L = mid + side` and `R = mid - side`. A mono input is spread to both sides first, so it is all mid. Off, both levels are unity and the sides keep their lows. Bass mono is a high-pass on the side only. It is a second-order Butterworth filter, so the sides are 3 dB down at the frequency, and a signal in the centre is untouched. Measured in Chrome, with the levels at 0 dB a centre signal and a side signal come out as they went in. A mid of -6 dB takes 6 dB off a centre signal and nothing off a side one, and a side of -24 dB or +6 dB moves a side signal by that much and leaves a centre one alone. With Bass mono at 200 Hz, a side signal at 50 Hz is 24 dB down, one at 100 Hz is 12 dB down, one at 400 Hz is 0.3 dB down and one at 2 kHz is untouched, and a centre signal at 50 Hz is untouched. --- # Multiband compressor > A multiband compressor device: two splits into three bands, a threshold and a ratio for each, a shared attack and release, a panel that draws the bands, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { MultibandPanel } from "@/components/audio-ui/devices/multiband/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { useSpectrum } from "@/hooks/use-spectrum"; import { type MultibandState, multibandDevice, } from "@/components/audio-ui/devices/multiband/device"; import { createMultibandEngine } from "@/components/audio-ui/devices/multiband/engine"; const MASTER_VOLUME = 0.7; const MIN_HZ = 20; const MAX_HZ = 20_000; /** * A multiband compressor you can plug in: its state, a panel that draws the * three bands and an engine that plays it, each its own file and none knowing * the others. Play the loop, lower the threshold of one band and only that * band is held down. */ export function BlockMultiband() { const [state, setState] = useState(() => multibandDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { analyser } = useDeviceLoop({ create: createMultibandEngine, destination: master, state, }); const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); return (
); } ``` Compresses three bands apart. The signal is split at two frequencies into low, mid and high, and each band has its own threshold and ratio. A loud bass does not pump the highs, and a harsh band can be held down without dulling the rest. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/multiband ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/multiband/`. The demo above, which wires them to a loop, is `@audio-ui/block-multiband`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/multiband-device @audio-ui/multiband-panel @audio-ui/multiband-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-multiband.tsx" "use client"; import { useState } from "react"; import { MultibandPanel } from "@/components/audio-ui/devices/multiband/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { useSpectrum } from "@/hooks/use-spectrum"; import { type MultibandState, multibandDevice, } from "@/components/audio-ui/devices/multiband/device"; import { createMultibandEngine } from "@/components/audio-ui/devices/multiband/engine"; const MASTER_VOLUME = 0.7; const MIN_HZ = 20; const MAX_HZ = 20_000; /** * A multiband compressor you can plug in: its state, a panel that draws the * three bands and an engine that plays it, each its own file and none knowing * the others. Play the loop, lower the threshold of one band and only that * band is held down. */ export function BlockMultiband() { const [state, setState] = useState(() => multibandDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { analyser } = useDeviceLoop({ create: createMultibandEngine, destination: master, state, }); const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the multiband from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Low split | 40 Hz to 1 kHz | 200 Hz | The frequency between the low band and the mid band. Set it with the left handle on the plot. | | High split | 1.2 kHz to 12 kHz | 3 kHz | The frequency between the mid band and the high band. Set it with the right handle on the plot. | | Low threshold | -60 dB to 0 dB | -24 dB | The level above which the low band is compressed. | | Low ratio | 1:1 to 20:1 | 3:1 | How much the low band is brought down above its threshold. | | Mid threshold | -60 dB to 0 dB | -26 dB | The level above which the mid band is compressed. | | Mid ratio | 1:1 to 20:1 | 3:1 | How much the mid band is brought down above its threshold. | | High threshold | -60 dB to 0 dB | -28 dB | The level above which the high band is compressed. | | High ratio | 1:1 to 20:1 | 3:1 | How much the high band is brought down above its threshold. | | Attack | 0.5 ms to 100 ms | 10 ms | How fast a band is taken down once it is over its threshold. The three bands share it. | | Release | 20 ms to 1000 ms | 150 ms | How fast a band comes back once it is under its threshold. The three bands share it. | | Output | -12 dB to 12 dB | 0 dB | The level of the three bands added back together. | ## Panel The panel draws the three bands against frequency, with a handle on each split to drag across. The splits have no knob. The two ranges do not overlap (40 to 1000 Hz and 1.2 to 12 kHz), so the splits can never cross. `multibandBands(state)` is what the panel draws: what each band keeps of the signal, in dB at each frequency. Pass a spectrum to the panel to see what comes out behind the curves. ```tsx import { MultibandPanel } from "@/components/audio-ui/devices/multiband/panel"; import { multibandDevice } from "@/components/audio-ui/devices/multiband/device"; const [state, setState] = useState(() => multibandDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). ```ts engine.reductions; // { low, mid, high }: dB taken off each band, read per frame ``` Two biquads in a row make one Linkwitz-Riley filter, whose halves add back to a flat response. The low band also goes through the two halves of the high split, added, so that it is shifted in phase as the other two are and the three add back flat. Each band has its own detector, the one of the compressor's [sidechain](/docs/devices#sidechain), with a soft knee of 6 dB. Measured in Chrome with all ratios at 1, the output is within 0.01 dB of the input from 60 Hz to 9 kHz. With a 100 Hz tone at -6 dB over a 6 kHz tone, a threshold of -30 dB at 8:1 on the low band takes 16.4 dB off the bass and nothing off the highs. The same on the high band takes 10.6 dB off the highs and nothing off the bass. --- # Overdrive > An overdrive device: a band-pass before a soft clip, a drive, a tone and a mix, a panel that draws the band that reaches the clip, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { OverdrivePanel } from "@/components/audio-ui/devices/overdrive/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { useSpectrum } from "@/hooks/use-spectrum"; import { type OverdriveState, overdriveDevice, } from "@/components/audio-ui/devices/overdrive/device"; import { createOverdriveEngine } from "@/components/audio-ui/devices/overdrive/engine"; const MASTER_VOLUME = 0.7; const MIN_HZ = 20; const MAX_HZ = 20_000; /** * An overdrive you can plug in: its state, a panel that draws the band that * reaches the clip and an engine that plays it, each its own file and none * knowing the others. Play the loop, drag the handle and turn the drive. */ export function BlockOverdrive() { const [state, setState] = useState(() => overdriveDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { analyser } = useDeviceLoop({ create: createOverdriveEngine, destination: master, state, }); const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); return (
); } ``` A pedal-style distortion. A band-pass filter picks what is pushed into the soft clip, so the lows do not turn to mud. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/overdrive ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/overdrive/`. The demo above, which wires them to a loop, is `@audio-ui/block-overdrive`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/overdrive-device @audio-ui/overdrive-panel @audio-ui/overdrive-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-overdrive.tsx" "use client"; import { useState } from "react"; import { OverdrivePanel } from "@/components/audio-ui/devices/overdrive/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { useSpectrum } from "@/hooks/use-spectrum"; import { type OverdriveState, overdriveDevice, } from "@/components/audio-ui/devices/overdrive/device"; import { createOverdriveEngine } from "@/components/audio-ui/devices/overdrive/engine"; const MASTER_VOLUME = 0.7; const MIN_HZ = 20; const MAX_HZ = 20_000; /** * An overdrive you can plug in: its state, a panel that draws the band that * reaches the clip and an engine that plays it, each its own file and none * knowing the others. Play the loop, drag the handle and turn the drive. */ export function BlockOverdrive() { const [state, setState] = useState(() => overdriveDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { analyser } = useDeviceLoop({ create: createOverdriveEngine, destination: master, state, }); const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the overdrive from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Band | 100 Hz to 8 kHz | 800 Hz | The centre of the band that reaches the clip. Drag the handle on the plot across to set it. | | Width | 0.30 to 6.00 | 0.80 | The width of that band. A high value is narrow. | | Drive | 0 dB to 40 dB | 14 dB | How hard the band is pushed into the clip. | | Tone | 500 Hz to 20 kHz | 4.5 kHz | Closes the highs after the clip. | | Mix | 0 % to 100 % | 80 % | The balance of the distorted signal and the clean one. | ## Panel The panel draws the band-pass that picks what reaches the clip, with a handle on its centre. `overdriveBand(state)` is the curve it draws. Pass a spectrum to the panel to see what comes out behind the curve. ```tsx import { OverdrivePanel } from "@/components/audio-ui/devices/overdrive/panel"; import { overdriveDevice } from "@/components/audio-ui/devices/overdrive/device"; const [state, setState] = useState(() => overdriveDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). Only what the band-pass lets through goes into the clip, and the clean sound goes round it in the dry path. The drive is a gain before one fixed soft-clip table, and the shaper oversamples 4x to keep the clip from aliasing. That oversampling is the [latency](/docs/devices#latency) of the device. --- # Phaser > A phaser device: a phaser or flanger mode, a rate or a note value, a depth, a centre frequency, a delay, a feedback and a mix, a panel that draws the sweep, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { PhaserPanel } from "@/components/audio-ui/devices/phaser/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type PhaserState, phaserDevice, } from "@/components/audio-ui/devices/phaser/device"; import { createPhaserEngine } from "@/components/audio-ui/devices/phaser/engine"; const MASTER_VOLUME = 0.7; /** * A phaser and flanger you can plug in: its state, a panel that draws the sweep and an engine that plays it, each its own file. Play the loop, switch the mode and turn the rate and the feedback. */ export function BlockPhaser() { const [state, setState] = useState(() => phaserDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { tempo } = useDeviceLoop({ create: createPhaserEngine, destination: master, state, }); return (
); } ``` Sweeps notches through the sound with a slow oscillator. In Phaser mode it is a chain of four all-pass filters around a centre frequency. In Flanger mode it is a very short delay. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/phaser ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/phaser/`. The demo above, which wires them to a loop, is `@audio-ui/block-phaser`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/phaser-device @audio-ui/phaser-panel @audio-ui/phaser-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-phaser.tsx" "use client"; import { useState } from "react"; import { PhaserPanel } from "@/components/audio-ui/devices/phaser/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type PhaserState, phaserDevice, } from "@/components/audio-ui/devices/phaser/device"; import { createPhaserEngine } from "@/components/audio-ui/devices/phaser/engine"; const MASTER_VOLUME = 0.7; /** * A phaser and flanger you can plug in: its state, a panel that draws the sweep and an engine that plays it, each its own file. Play the loop, switch the mode and turn the rate and the feedback. */ export function BlockPhaser() { const [state, setState] = useState(() => phaserDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); const { tempo } = useDeviceLoop({ create: createPhaserEngine, destination: master, state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the phaser from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Mode | Phaser, Flanger | Phaser | Phaser sweeps the filters, Flanger sweeps the delay. The controls the mode does not use are drawn off. | | Rate | 0.05 Hz to 10.00 Hz | 0.40 Hz | How fast the oscillator sweeps. | | Sync | On or off | Off | Takes the rate from a note value and the tempo of the host. See [Tempo sync](/docs/devices#tempo-sync). | | Note | 1/32 triplet, 1/32, 1/32 dotted, 1/16 triplet, 1/16, 1/16 dotted, 1/8 triplet, 1/8, 1/8 dotted, 1/4 triplet, 1/4, 1/4 dotted, 1/2 triplet, 1/2, 1/2 dotted, 1/1 triplet, 1/1, 1/1 dotted | 1/4 | The note value of one cycle of the oscillator. | | Depth | 0 % to 100 % | 60 % | How far the oscillator moves the filters or the delay. | | Center | 200 Hz to 8 kHz | 1.2 kHz | The frequency the phaser sweeps around. | | Delay | 0.5 ms to 10 ms | 3 ms | The delay the flanger sweeps around. | | Feedback | 0 % to 90 % | 40 % | How much of the output goes back in, which deepens the notches. | | Mix | 0 % to 100 % | 50 % | The balance of the processed signal and the dry one. | ## Panel The panel draws what the oscillator does over two seconds. `phaserSweep(state)` is what it draws, and `phaserSettings(state)` gives the numbers that go on the nodes. ```tsx import { PhaserPanel } from "@/components/audio-ui/devices/phaser/panel"; import { phaserDevice } from "@/components/audio-ui/devices/phaser/device"; const [state, setState] = useState(() => phaserDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). Both paths are always built and the mode crossfades them, so switching does not click. One oscillator moves the filters, in cents, and the delay, in seconds. The flanger's sweep is kept inside its delay so the time never goes negative. --- # Pocket synth > A synth device: a waveform, a filter and a volume, a panel with a pad that plays it, a Web Audio engine with noteOn and noteOff, and tools for agents. ```tsx "use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { PocketSynthPanel } from "@/components/audio-ui/devices/pocket-synth/panel"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type PocketSynthNote, type PocketSynthState, pocketSynthDevice, } from "@/components/audio-ui/devices/pocket-synth/device"; import { createPocketSynthEngine, type PocketSynthEngine, } from "@/components/audio-ui/devices/pocket-synth/engine"; import { webAudio } from "@/lib/web-audio"; /** * A synth you can plug in: its state, a panel that draws and plays it and an * engine that makes the sound, each its own file and none knowing the others. * Press the pad and move: pitch goes across, the filter cutoff up. */ export function BlockPocketSynth() { const [state, setState] = useState(() => pocketSynthDevice.defaults() ); const master = useMasterBus(1); const [engine, setEngine] = useState(null); const stateRef = useRef(state); stateRef.current = state; useEffect(() => { const ctx = webAudio.getContext(); if (!(ctx && master)) { return; } const synth = createPocketSynthEngine(ctx, stateRef.current); synth.output.connect(master); setEngine(synth); return () => { synth.dispose(); setEngine(null); }; }, [master]); // The engine follows the state, whoever changed it: a button or a call. useEffect(() => { engine?.update(state); }, [engine, state]); const play = useCallback( (note: PocketSynthNote) => engine?.noteOn(note), [engine] ); const release = useCallback(() => engine?.noteOff(), [engine]); return (
); } ``` One oscillator through a resonant filter. Press the pad: the pitch goes across and the filter cutoff goes up. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/pocket-synth ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/pocket-synth/`. The demo above, which wires them to a loop, is `@audio-ui/block-pocket-synth`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/pocket-synth-device @audio-ui/pocket-synth-panel @audio-ui/pocket-synth-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-pocket-synth.tsx" "use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { PocketSynthPanel } from "@/components/audio-ui/devices/pocket-synth/panel"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type PocketSynthNote, type PocketSynthState, pocketSynthDevice, } from "@/components/audio-ui/devices/pocket-synth/device"; import { createPocketSynthEngine, type PocketSynthEngine, } from "@/components/audio-ui/devices/pocket-synth/engine"; import { webAudio } from "@/lib/web-audio"; /** * A synth you can plug in: its state, a panel that draws and plays it and an * engine that makes the sound, each its own file and none knowing the others. * Press the pad and move: pitch goes across, the filter cutoff up. */ export function BlockPocketSynth() { const [state, setState] = useState(() => pocketSynthDevice.defaults() ); const master = useMasterBus(1); const [engine, setEngine] = useState(null); const stateRef = useRef(state); stateRef.current = state; useEffect(() => { const ctx = webAudio.getContext(); if (!(ctx && master)) { return; } const synth = createPocketSynthEngine(ctx, stateRef.current); synth.output.connect(master); setEngine(synth); return () => { synth.dispose(); setEngine(null); }; }, [master]); // The engine follows the state, whoever changed it: a button or a call. useEffect(() => { engine?.update(state); }, [engine, state]); const play = useCallback( (note: PocketSynthNote) => engine?.noteOn(note), [engine] ); const release = useCallback(() => engine?.noteOff(), [engine]); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the pocket synth from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | Wave | Sine, Triangle, Saw, Square | Square | The wave of the oscillator. | | Filter | All pass, Low pass, High pass, Band pass | All pass | The type of the filter. | | Volume | 0% to 100% | 50% | The level of the output. | ## Panel The panel has a pad that plays the synth: its position gives the note, so the pitch goes across and the cutoff goes up. `pocketSynthPitch(position)` and `pocketSynthCutoff(position)` turn a position from 0 to 1 into hertz. The panel sends notes out and does not make the sound, so it plays through any engine. ```tsx import { PocketSynthPanel } from "@/components/audio-ui/devices/pocket-synth/panel"; import { pocketSynthDevice } from "@/components/audio-ui/devices/pocket-synth/device"; const [state, setState] = useState(() => pocketSynthDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). ```ts engine.noteOn(note); // starts a note now, or glides the one being held engine.noteOff(); // lets it go // Scheduled ahead on the audio clock, by a host that plays notes from a song: engine.noteOn({ ...note, velocity: 0.8 }, { at: time, id: "c4" }); engine.noteOff({ at: time + length, id: "c4" }); ``` One voice at a time. `noteOn` starts a note, or glides the one being held to the new one, and `noteOff` releases it. Both take an optional `{ at, id }`: `at` is a time of the audio clock, now when there is none, and a `noteOff` whose `id` is not the held note's lets nothing go, since the held note took over from it. A note plays as loud as its `velocity`, from 0 to 1. The wave and the filter type of a state change under a held note. An agent plays the synth with the `play` tool. --- # Redux > A redux device: a number of bits, a downsample factor and a mix, a panel that draws the stairs the bits make, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { ReduxPanel } from "@/components/audio-ui/devices/redux/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type ReduxState, reduxDevice, } from "@/components/audio-ui/devices/redux/device"; import { createReduxEngine } from "@/components/audio-ui/devices/redux/engine"; const MASTER_VOLUME = 0.7; /** * A redux you can plug in: its state, a panel that draws the stairs the bits * make and an engine that plays it, each its own file and none knowing the * others. Play the loop and take the bits down: the stairs grow as the sound * roughens. */ export function BlockRedux() { const [state, setState] = useState(() => reduxDevice.defaults()); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createReduxEngine, destination: master, state, }); return (
); } ``` Roughens the sound like an early sampler. It keeps only some bits of each sample and holds each sample for several. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/redux ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/redux/`. The demo above, which wires them to a loop, is `@audio-ui/block-redux`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/redux-device @audio-ui/redux-panel @audio-ui/redux-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-redux.tsx" "use client"; import { useState } from "react"; import { ReduxPanel } from "@/components/audio-ui/devices/redux/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type ReduxState, reduxDevice, } from "@/components/audio-ui/devices/redux/device"; import { createReduxEngine } from "@/components/audio-ui/devices/redux/engine"; const MASTER_VOLUME = 0.7; /** * A redux you can plug in: its state, a panel that draws the stairs the bits * make and an engine that plays it, each its own file and none knowing the * others. Play the loop and take the bits down: the stairs grow as the sound * roughens. */ export function BlockRedux() { const [state, setState] = useState(() => reduxDevice.defaults()); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createReduxEngine, destination: master, state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the redux from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Bits | 1 to 16 | 8 | How many bits each sample keeps. At 8 the stairs are too fine to see: take it down to 3 or 4. | | Downsample | 1x to 64x | 4x | How many samples each one is held for. | | Mix | 0 % to 100 % | 100 % | The balance of the roughened signal and the clean one. | ## Panel The panel draws the stairs the bits make against the straight line of a clean sound. `quantize(input, bits)` is one step of the quantizer. ```tsx import { ReduxPanel } from "@/components/audio-ui/devices/redux/panel"; import { reduxDevice } from "@/components/audio-ui/devices/redux/device"; const [state, setState] = useState(() => reduxDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). The bits are a quantizer table in a `WaveShaperNode`, rebuilt only when they change. The sample hold is an `AudioWorklet` (`REDUX_WORKLET` is its source). Until it is ready the bits are already crushed and the rate is not yet reduced, and `engine.ready` resolves to `false` in a context that cannot run worklets. The hold takes whole samples, not a filtered resampling, so it aliases, which is the sound. --- # Reverb > A reverb device: a decay, a pre-delay, a damping and a mix, a panel that draws the tail with a handle, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { ReverbPanel } from "@/components/audio-ui/devices/reverb/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type ReverbState, reverbDevice, } from "@/components/audio-ui/devices/reverb/device"; import { createReverbEngine } from "@/components/audio-ui/devices/reverb/engine"; const MASTER_VOLUME = 0.7; /** * A reverb you can plug in: its state, a panel that draws the tail it makes * and an engine that plays it, each its own file and none knowing the others. * Play the loop and drag the handle along: the decay time. */ export function BlockReverb() { const [state, setState] = useState(() => reverbDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createReverbEngine, destination: master, state, }); return (
); } ``` Puts the sound in a room. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/reverb ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/reverb/`. The demo above, which wires them to a loop, is `@audio-ui/block-reverb`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/reverb-device @audio-ui/reverb-panel @audio-ui/reverb-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-reverb.tsx" "use client"; import { useState } from "react"; import { ReverbPanel } from "@/components/audio-ui/devices/reverb/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type ReverbState, reverbDevice, } from "@/components/audio-ui/devices/reverb/device"; import { createReverbEngine } from "@/components/audio-ui/devices/reverb/engine"; const MASTER_VOLUME = 0.7; /** * A reverb you can plug in: its state, a panel that draws the tail it makes * and an engine that plays it, each its own file and none knowing the others. * Play the loop and drag the handle along: the decay time. */ export function BlockReverb() { const [state, setState] = useState(() => reverbDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createReverbEngine, destination: master, state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the reverb from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Decay | 0.2 s to 10 s | 2.2 s | How long the tail takes to fall by 60 dB. Drag the handle at the end of the tail to set it. | | Pre-delay | 0 ms to 200 ms | 20 ms | The time between the sound and the start of the tail. | | Damping | 1 kHz to 20 kHz | 7 kHz | Closes the highs of the tail, as soft walls do. | | Mix | 0 % to 100 % | 25 % | The balance of the room and the dry signal. | ## Panel The panel draws the level of the tail falling in dB, from the end of the pre-delay to -60 dB. `reverbDecay(state)` is the curve it draws, and `reverbImpulse(sampleRate, state)` makes the impulse response of the room. ```tsx import { ReverbPanel } from "@/components/audio-ui/devices/reverb/panel"; import { reverbDevice } from "@/components/audio-ui/devices/reverb/device"; const [state, setState] = useState(() => reverbDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). The room is a convolver fed an impulse response made from the decay and the damping. A convolver cannot change its impulse without a click, so the engine has two and cross-fades: a new room is built in the idle one, at most every 120 ms while a control moves. --- # Saturator > A saturator device: four curves, a drive, a mix and an output, a panel that draws the transfer curve, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { SaturatorPanel } from "@/components/audio-ui/devices/saturator/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type SaturatorState, saturatorDevice, } from "@/components/audio-ui/devices/saturator/device"; import { createSaturatorEngine } from "@/components/audio-ui/devices/saturator/engine"; const MASTER_VOLUME = 0.7; /** * A saturator you can plug in: its state, a panel that draws its transfer * curve and an engine that plays it, each its own file and none knowing the * others. Play the loop, pick a curve and turn the drive: the curve bends as * the sound does. */ export function BlockSaturator() { const [state, setState] = useState(() => saturatorDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createSaturatorEngine, destination: master, state, }); return (
); } ``` Adds warmth or dirt. The drive pushes the signal into one of four curves: a soft clip, a hard clip, a wavefold or an asymmetric tube. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/saturator ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/saturator/`. The demo above, which wires them to a loop, is `@audio-ui/block-saturator`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/saturator-device @audio-ui/saturator-panel @audio-ui/saturator-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-saturator.tsx" "use client"; import { useState } from "react"; import { SaturatorPanel } from "@/components/audio-ui/devices/saturator/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type SaturatorState, saturatorDevice, } from "@/components/audio-ui/devices/saturator/device"; import { createSaturatorEngine } from "@/components/audio-ui/devices/saturator/engine"; const MASTER_VOLUME = 0.7; /** * A saturator you can plug in: its state, a panel that draws its transfer * curve and an engine that plays it, each its own file and none knowing the * others. Play the loop, pick a curve and turn the drive: the curve bends as * the sound does. */ export function BlockSaturator() { const [state, setState] = useState(() => saturatorDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createSaturatorEngine, destination: master, state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the saturator from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Curve | Soft, Hard, Fold, Tube | Soft | The shape of the saturation. | | Drive | 0 dB to 36 dB | 9 dB | How hard the signal is pushed into the curve. | | Mix | 0 % to 100 % | 100 % | The balance of the saturated signal and the clean one. | | Output | -24 dB to 12 dB | -3 dB | The level of the output. | ## Panel The panel draws the transfer curve against the straight line of a clean sound. `saturate(curve, input)` is one curve and `saturatorCurve(state)` is the whole transfer curve with the mix and the output. ```tsx import { SaturatorPanel } from "@/components/audio-ui/devices/saturator/panel"; import { saturatorDevice } from "@/components/audio-ui/devices/saturator/device"; const [state, setState] = useState(() => saturatorDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). The drive is a gain before the table of the curve, so turning it never rebuilds the table. Only picking another curve does. The shaper oversamples 4x to keep the clip from aliasing, which is the [latency](/docs/devices#latency) of the device. --- # Transient shaper > A transient shaper device: attack and sustain, each up or down by 12 dB, a panel with one handle for both, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { TransientPanel } from "@/components/audio-ui/devices/transient/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type TransientState, transientDevice, } from "@/components/audio-ui/devices/transient/device"; import { createTransientEngine } from "@/components/audio-ui/devices/transient/engine"; const MASTER_VOLUME = 0.7; /** * A transient shaper you can plug in: its state, a panel with a handle for * the attack and the sustain and an engine that plays it, each its own file * and none knowing the others. Play the loop and drag the handle: up for more * click, down to soften it, left to shorten what rings. */ export function BlockTransient() { const [state, setState] = useState(() => transientDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createTransientEngine, destination: master, state, }); return (
); } ``` Shapes the attack and the sustain of a sound, at any level. A drum gains click or loses it, and a pluck rings longer or shorter. There is no threshold, so a quiet hit and a loud one are shaped alike. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/transient ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/transient/`. The demo above, which wires them to a loop, is `@audio-ui/block-transient`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/transient-device @audio-ui/transient-panel @audio-ui/transient-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-transient.tsx" "use client"; import { useState } from "react"; import { TransientPanel } from "@/components/audio-ui/devices/transient/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type TransientState, transientDevice, } from "@/components/audio-ui/devices/transient/device"; import { createTransientEngine } from "@/components/audio-ui/devices/transient/engine"; const MASTER_VOLUME = 0.7; /** * A transient shaper you can plug in: its state, a panel with a handle for * the attack and the sustain and an engine that plays it, each its own file * and none knowing the others. Play the loop and drag the handle: up for more * click, down to soften it, left to shorten what rings. */ export function BlockTransient() { const [state, setState] = useState(() => transientDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createTransientEngine, destination: master, state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the transient from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Attack | -12 dB to 12 dB | 6 dB | Turns the start of a hit up or down. | | Sustain | -12 dB to 12 dB | 0 dB | Turns what rings after the hit up or down. | | Output | -12 dB to 12 dB | 0 dB | The level of the output. | ## Panel The panel is a square with the sustain across and the attack up, and one handle to drag to both at once. The centre is a sound left as it is. ```tsx import { TransientPanel } from "@/components/audio-ui/devices/transient/panel"; import { transientDevice } from "@/components/audio-ui/devices/transient/device"; const [state, setState] = useState(() => transientDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). The browser has no such node, so a detector reads the signal as an `AudioWorklet` and writes the gain to apply. It follows the peak of the signal, which jumps up and falls over 15 ms so a low note does not ripple it, and the same peak smoothed over 25 ms. They meet when a sound holds and part when a hit starts. How far the peak is over the smoothed one says how much of the moment is attack (6 dB or more is all of it), and the rest is sustain. Only the shape of the envelope counts, not its level. The audio waits a millisecond for the detector, so the gain is up when a hit arrives. That is the [latency](/docs/devices#latency) of the device. Measured in Chrome on a decaying tone, the sustain moves the tail by what the control says, to the hundredth (+9 gives +9.00 dB and -9 gives -9.00 dB at 60, 200 and 2000 Hz). The attack leaves the tail alone, and +9 on the attack raises the first peak by 8.7 dB, at a level of -6 dB or of -26 dB alike. Taking the attack down lowers the peak by 6 to 7 dB for -9, since the gain needs a moment to fall. --- # Utility > A utility device: a gain, a pan, a width, a mono switch and a phase invert, a panel without a display, a Web Audio engine and tools for agents. ```tsx "use client"; import { useState } from "react"; import { UtilityPanel } from "@/components/audio-ui/devices/utility/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type UtilityState, utilityDevice, } from "@/components/audio-ui/devices/utility/device"; import { createUtilityEngine } from "@/components/audio-ui/devices/utility/engine"; const MASTER_VOLUME = 0.7; /** * A utility you can plug in: its state, a panel and an engine that plays it, each its own file and none knowing the others. Play the loop and move the pan and the width. */ export function BlockUtility() { const [state, setState] = useState(() => utilityDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createUtilityEngine, destination: master, state, }); return (
); } ``` Sets the level and the stereo image of a signal. It has no display, so its panel is only as tall as its controls. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/utility ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/utility/`. The demo above, which wires them to a loop, is `@audio-ui/block-utility`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/utility-device @audio-ui/utility-panel @audio-ui/utility-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-utility.tsx" "use client"; import { useState } from "react"; import { UtilityPanel } from "@/components/audio-ui/devices/utility/panel"; import { useDeviceLoop } from "@/hooks/use-device-loop"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type UtilityState, utilityDevice, } from "@/components/audio-ui/devices/utility/device"; import { createUtilityEngine } from "@/components/audio-ui/devices/utility/engine"; const MASTER_VOLUME = 0.7; /** * A utility you can plug in: its state, a panel and an engine that plays it, each its own file and none knowing the others. Play the loop and move the pan and the width. */ export function BlockUtility() { const [state, setState] = useState(() => utilityDevice.defaults() ); const master = useMasterBus(MASTER_VOLUME); useDeviceLoop({ create: createUtilityEngine, destination: master, state, }); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the utility from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | On | On or off | On | Turns the device on. Off, the signal passes through unchanged. | | Gain | -35 dB to 35 dB | 0 dB | The level of the signal. | | Pan | L100 to R100 | C | Moves the signal between the left and the right. | | Width | 0 % to 200 % | 100 % | The width of the stereo image. 0 is mono, 100 % is the input as it is and 200 % is twice as wide. | | Mono | On or off | Off | Sums the two channels to one. | | Invert | On or off | Off | Flips the phase of the signal. | ## Panel The panel is the controls and nothing else. `utilitySettings(state)` gives the numbers that go on the nodes. ```tsx import { UtilityPanel } from "@/components/audio-ui/devices/utility/panel"; import { utilityDevice } from "@/components/audio-ui/devices/utility/device"; const [state, setState] = useState(() => utilityDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). The signal is split into mid and side, and the width scales the side. A mono input is spread to both sides first. Off, the signal passes unchanged. --- # Wave shaper > A wave shaper synth device: a waveform, a drive, a tone, a detune, a mix and a volume, a panel with a pad that plays it, a Web Audio engine with noteOn and noteOff, and tools for agents. ```tsx "use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { WaveShaperPanel } from "@/components/audio-ui/devices/wave-shaper/panel"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type WaveShaperNote, type WaveShaperState, waveShaperDevice, } from "@/components/audio-ui/devices/wave-shaper/device"; import { createWaveShaperEngine, type WaveShaperEngine, } from "@/components/audio-ui/devices/wave-shaper/engine"; import { webAudio } from "@/lib/web-audio"; /** * A wave shaper synth you can plug in: its state, a panel that draws and plays * it and an engine that makes the sound, each its own file and none knowing * the others. Press the pad and move: pitch goes across, the resonance up. */ export function BlockWaveShaper() { const [state, setState] = useState(() => waveShaperDevice.defaults() ); const master = useMasterBus(1); const [engine, setEngine] = useState(null); const stateRef = useRef(state); stateRef.current = state; useEffect(() => { const ctx = webAudio.getContext(); if (!(ctx && master)) { return; } const synth = createWaveShaperEngine(ctx, stateRef.current); synth.output.connect(master); setEngine(synth); return () => { synth.dispose(); setEngine(null); }; }, [master]); // The engine follows the state, whoever changed it: a button or a knob. useEffect(() => { engine?.update(state); }, [engine, state]); const play = useCallback( (note: WaveShaperNote) => engine?.noteOn(note), [engine] ); const release = useCallback(() => engine?.noteOff(), [engine]); return (
); } ``` Two detuned oscillators, a distortion mixed in with the clean sound, and a low-pass filter. Press the pad: the pitch goes across and the resonance goes up. It is a [device](/docs/devices): a state, a panel, an engine and tools, each its own file. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/wave-shaper ``` It installs the device's state, its engine and its panel to `components/audio-ui/devices/wave-shaper/`. The demo above, which wires them to a loop, is `@audio-ui/block-wave-shaper`. **Manual** **1. Install the packages:** ```bash npm install @audio-ui/react @audio-ui/core ``` **2. Add the pieces you want. All of them, or only the state and the panel if your engine is elsewhere:** ```bash npx shadcn@latest add @audio-ui/wave-shaper-device @audio-ui/wave-shaper-panel @audio-ui/wave-shaper-engine ``` **3. Copy and paste the demo that wires them, if you want it.** ```tsx title="components/examples/block-wave-shaper.tsx" "use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { WaveShaperPanel } from "@/components/audio-ui/devices/wave-shaper/panel"; import { useMasterBus } from "@/hooks/use-master-bus"; import { type WaveShaperNote, type WaveShaperState, waveShaperDevice, } from "@/components/audio-ui/devices/wave-shaper/device"; import { createWaveShaperEngine, type WaveShaperEngine, } from "@/components/audio-ui/devices/wave-shaper/engine"; import { webAudio } from "@/lib/web-audio"; /** * A wave shaper synth you can plug in: its state, a panel that draws and plays * it and an engine that makes the sound, each its own file and none knowing * the others. Press the pad and move: pitch goes across, the resonance up. */ export function BlockWaveShaper() { const [state, setState] = useState(() => waveShaperDevice.defaults() ); const master = useMasterBus(1); const [engine, setEngine] = useState(null); const stateRef = useRef(state); stateRef.current = state; useEffect(() => { const ctx = webAudio.getContext(); if (!(ctx && master)) { return; } const synth = createWaveShaperEngine(ctx, stateRef.current); synth.output.connect(master); setEngine(synth); return () => { synth.dispose(); setEngine(null); }; }, [master]); // The engine follows the state, whoever changed it: a button or a knob. useEffect(() => { engine?.update(state); }, [engine, state]); const play = useCallback( (note: WaveShaperNote) => engine?.noteOn(note), [engine] ); const release = useCallback(() => engine?.noteOff(), [engine]); return (
); } ``` **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the wave shaper from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Controls | Control | Range | Default | What it does | | --- | --- | --- | --- | | Wave | Sine, Triangle, Saw, Square | Sine | The wave of the oscillators. | | Drive | 0 to 100 | 1 | How much of the distortion is pushed into the sound. | | Tone | 0 to 100 | 50 | The cutoff of the low-pass filter. | | Detune | -50 ct to 50 ct | 0 ct | How far apart the two oscillators are tuned. | | Mix | 0 % to 100 % | 50 % | The balance of the distorted signal and the clean one. | | Volume | 0% to 100% | 50% | The level of the output. | ## Panel The panel has a pad that plays the synth: the pitch goes across and the resonance goes up. `waveShaperPitch(position)` and `waveShaperResonance(position)` turn a position from 0 to 1 into a note. ```tsx import { WaveShaperPanel } from "@/components/audio-ui/devices/wave-shaper/panel"; import { waveShaperDevice } from "@/components/audio-ui/devices/wave-shaper/device"; const [state, setState] = useState(() => waveShaperDevice.defaults()); ; ``` ## Engine Create it, connect it and update it as for any device: see [The engine](/docs/devices#the-engine). ```ts engine.noteOn(note); // starts a note now, or glides the one being held engine.noteOff(); // lets it go // Scheduled ahead on the audio clock, by a host that plays notes from a song: engine.noteOn({ ...note, velocity: 0.8 }, { at: time, id: "c4" }); engine.noteOff({ at: time + length, id: "c4" }); ``` One voice at a time, as the [pocket synth](/docs/components/base/pocket-synth). The distortion curve is a table of 44,100 points, rebuilt only when the drive changes. The shaper oversamples 4x, which delays its path by 4 ms, and the clean path waits as long so the mix does not comb. --- # Envelope > An editor for a breakpoint ramp, such as an ADSR shape or an automation curve. ```tsx import { Envelope } from "@/components/audio-ui/envelope"; export function EnvelopeSizeDefaultDemo() { return ; } ``` Edits a ramp made of breakpoints, such as an ADSR shape or an automation curve. The registry component wraps the `Envelope` primitive from `@audio-ui/react` and draws the points, the segments between them and a grid. ## Overview - **Value:** `value` is a list of `{ x, y, curve? }` points. Both axes are normalized to 0…1, and the points are sorted by `x`. Map that range to your own unit, such as time or level. - **Curves:** a point's `curve`, from -1 to 1, bends the segment that leaves it. 0, or no value, draws a straight line. A positive curve holds the start of the segment and steepens its end; a negative curve is its mirror image, rushing the start and holding the end. The bend is the exponential of an analog envelope stage, `(e^(k·t) - 1) / (e^k - 1)` with `k` the curve times 11, so neither end turns vertical. The last point has no segment. - **Pointer:** drag a point to move it. Double-click empty space to add a point, or double-click a point to remove it. A point stays between its neighbors, so points never cross. - **Point count:** points are added and removed between `minPoints` (default `2`, a start and an end) and `maxPoints`. Set both to the same number to fix the shape. - **Grid:** `snap` sets the grid that points snap to, for example `0.25` for quarters, or one step per axis, `{ x: 0.125, y: 0 }`, to snap across and leave the level free. Hold Cmd/Ctrl to move off the grid. Without `snap`, points move freely. The registry component draws the grid. - **Fine control:** hold Shift while dragging to move a point at a quarter of the pointer's speed. The registry component shows the point's value above it while it is dragged or focused. - **Accessibility:** the points share one tab stop. The arrow keys move the focused point, Page Up and Page Down (or Home and End) move between points, and Delete or Backspace removes it. Each point is a `role="slider"`. The registry component names the points "Point n of N". With the primitive, set `aria-label` and `getAriaValueText` yourself. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/envelope ``` **Manual** **1. Install the following dependencies:** ```bash npm install @audio-ui/react class-variance-authority ``` **2. Copy and paste the following code into your project.** ```tsx title="components/audio-ui/envelope.tsx" "use client"; import { Envelope as EnvelopePrimitive } from "@audio-ui/react"; import { cva, type VariantProps } from "class-variance-authority"; import { type CSSProperties, useCallback } from "react"; import { cn } from "@/lib/utils"; const envelopeVariants = cva("", { defaultVariants: { size: "default", }, variants: { size: { default: "h-48", lg: "h-64", sm: "h-32", }, }, }); /** The frame's room for the end points, which the grid's lines are measured from. */ const INSET = "0.875rem"; const DEFAULT_GRID_STEP = 0.25; /** A segment's bend as a signed percentage: positive holds the start of the segment, negative the end. */ const describeCurve = (curve = 0) => `Curve ${curve > 0 ? "+" : ""}${Math.round(curve * 100)}%`; /** Above this level a point's label sits under it, not over it. */ const LABEL_FLIP_ABOVE = 0.8; /** A grid step, or the default one where an axis has none. */ const gridStep = (step: number | undefined) => step && step > 0 ? step : DEFAULT_GRID_STEP; /** A line every step of `snap` across and down, spread over the whole frame like a plot's: they sit on the data's own coordinates, so a point is on a line at 0, ¼, ½, ¾ and 1. */ function gridLines(snap: EnvelopePrimitive.Root.Props["snap"]): CSSProperties { const [x, y] = typeof snap === "object" ? [snap.x, snap.y] : [snap, snap]; const share = (step: number | undefined) => `calc((100% - 2 * ${INSET}) * ${gridStep(step)})`; return { backgroundImage: "linear-gradient(to right, var(--border) 1px, transparent 1px), linear-gradient(to bottom, var(--border) 1px, transparent 1px)", backgroundPosition: `${INSET} 0, 0 ${INSET}`, backgroundSize: `${share(x)} 100%, 100% ${share(y)}`, }; } type Domain = readonly [number, number]; /** A share of the axis as a value in the axis's own units, to three significant digits. */ function describeAxis(share: number, domain?: Domain, unit = "") { const [min, max] = domain ?? [0, 100]; const value = Number((min + share * (max - min)).toPrecision(3)); const text = domain ? String(value) : `${Math.round(share * 100)}`; const suffix = domain ? unit : "%"; return suffix === "%" ? `${text}%` : `${text} ${suffix}`.trim(); } interface EnvelopeProps extends EnvelopePrimitive.Root.Props, VariantProps { /** Whether a handle on each segment bends it. @default true */ curves?: boolean; /** Prints a point's value in the label that shows while it is dragged or focused, and in its accessible value text. Defaults to the values in `xDomain` and `yDomain`, or percentages. */ formatValue?: (point: { x: number; y: number }) => string; /** The values the horizontal axis runs from and to, for the labels: `[0, 2000]` with `xUnit="ms"`. Unset, it reads in percent. */ xDomain?: Domain; xUnit?: string; /** The values the vertical axis runs from and to, for the labels. */ yDomain?: Domain; yUnit?: string; } /** * The frame has room inside it, so the first and last points sit within it * instead of on its edge. Drag a point to move it, the small handle on a * segment to bend it, and hold Shift for a fine drag. With `snap`, the grid's * lines are the snapping ones. */ export function Envelope({ className, curves = true, formatValue, size, snap, xDomain, xUnit, yDomain, yUnit, ...props }: EnvelopeProps) { const describe = useCallback( (point: { x: number; y: number }) => formatValue ? formatValue(point) : `${describeAxis(point.x, xDomain, xUnit)} · ${describeAxis(point.y, yDomain, yUnit)}`, [formatValue, xDomain, xUnit, yDomain, yUnit] ); return (
{curves ? ( {(point, index) => ( )} ) : null} {(point, index, points) => ( )}
); } ``` **3. Update the import paths to match your project setup.** **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the envelope from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Anatomy Import the primitive and assemble its parts. ```tsx import { Envelope } from "@audio-ui/react"; ``` ## Usage ```tsx import { Envelope } from "@/components/audio-ui/envelope"; ``` **Uncontrolled:** set only the initial points. ```tsx ``` **Controlled:** drive the points from state. ```tsx const [points, setPoints] = useState(initialPoints); console.log("Committed:", next, details.reason)} value={points} /> ``` ## Interaction ### Pointer **Behavior** | Gesture | Effect | | --- | --- | | Drag a point | Moves it; `x` stays between its neighbors and `y` within 0…1. Dragging never deletes a point. While dragging, the point follows the pointer even if a controlled `value` updates late. | | Double-click empty space | Adds a point at that location, unless at `maxPoints`. Added on a bent segment it sits on the curve, and each half is bent to keep its shape. | | Double-click a point | Removes it, unless at `minPoints`. | | Hold Shift while dragging a point | Moves it at a quarter of the pointer's speed, for fine adjustments. The point does not jump when Shift is pressed or released mid-drag. | | Alt + drag a segment | Bends it, like a DAW's automation lane: the segment's midpoint follows the pointer. A flat segment, or a press away from any segment, does nothing. | | Alt + double-click a segment | Straightens it, instead of adding a point. | | Alt + click a point | Removes it, unless at `minPoints`. | | Drag a segment's handle | Bends the segment: its midpoint follows the pointer up or down. A segment between two points of the same level has nothing to bend. | | Double-click a segment's handle | Straightens the segment. | | Commit event | `onValueCommitted` fires when a drag that moved a point ends, and right away for an add or a remove. | A refused add or remove sets `data-blocked` for a moment on the graph or the point, which the registry styles turn into a short shake. ### Keyboard The points share one tab stop. On the focused point: **Keys** | Key | Effect | | --- | --- | | `ArrowUp` / `ArrowDown` | Nudge the focused point's `y` by `step` | | `ArrowLeft` / `ArrowRight` | Nudge the focused point's `x` by `step` (clamped between neighbors) | | `Shift` + arrow | Nudge by 10 steps | | `PageUp` / `PageDown` | Move focus to the next or previous point | | `Home` / `End` | Move focus to the first or last point | | `Delete` / `Backspace` | Remove the focused point, unless at `minPoints` | Each segment has a handle on its curve. The handles share one tab stop: **Keys** | Key | Effect | | --- | --- | | `ArrowLeft` / `ArrowRight` | Move to the previous or next segment's handle | | `ArrowUp` / `ArrowDown` | Lift or lower the handle, bending the segment by 5 steps | | `Shift` + arrow | Bend by 50 steps | | `Delete` / `Backspace` | Straighten the segment | ## API reference ### Root Groups all parts of the breakpoint envelope and owns its points, each normalized to 0…1 on both axes and kept sorted by `x`. Points are dragged and nudged with the keyboard; a double click on the `Graph` adds one and a double click (or Delete) on a `Point` removes it, within `minPoints` / `maxPoints`. Renders a `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `defaultValue` | `GeomPoint[]` | | Uncontrolled starting points. Defaults to an ADSR-like shape. | | `disabled` | `boolean` | | | | `format` | `Intl.NumberFormatOptions` | | Formats point coordinates for each point's `aria-valuetext`. | | `locale` | `Intl.LocalesArgument` | | | | `maxPoints` | `number` | | Ceiling on the number of points; adding is blocked at this count. Equal to `minPoints`, the shape is fixed. | | `minPoints` | `number` | `2` | Floor on the number of points; removal is blocked at this count. | | `onValueChange` | `(value: GeomPoint[], eventDetails: ChangeEventDetails) => void` | | Fires on every change: drag, keyboard, add and remove. | | `onValueCommitted` | `(value: GeomPoint[], eventDetails: CommitEventDetails) => void` | | Fires when an interaction that changed the points ends. | | `step` | `number` | `0.01` | Keyboard step on both axes, in normalized units. | | `snap` | `number \| { x: number; y: number }` | `0` | Grid the pointer snaps points to, in normalized units: 0.25 snaps to quarters, 0 is no grid, and `{ x, y }` sets a step for each axis (`{ x: 0.125, y: 0 }` snaps across and leaves the level free). Holding Cmd/Ctrl leaves the grid, and Shift's fine drag ignores it. Keys move by `step`. | | `value` | `GeomPoint[]` | | | **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-dragging` | Whether a point is being dragged. | ### Graph The drawing surface, a 100×100 stretched viewBox: holds `Line` and `Fill`, and a double click on it adds a point. Carries `data-blocked` briefly when adding is refused at `maxPoints`. Renders a `` element. **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-dragging` | Whether a point is being dragged. | | `data-blocked` | Briefly true after an add was refused at `maxPoints`. | ### Line The envelope curve through the points. Renders a `` element. **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-dragging` | Whether a point is being dragged. | ### Fill The area under the curve. Renders a `` element. **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-dragging` | Whether a point is being dragged. | ### Points Renders one child per point, in `x` order. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `children` | `(point: GeomPoint, index: number, points: GeomPoint[]) => React.ReactNode` | | | ### Point A draggable handle for the point at `index`, positioned with `left`/`bottom` percentages over the `Graph`. It is a `role="slider"` on the point's level (`y`): give it an `aria-label`. One point at a time is the tab stop; arrow keys move it (Shift for larger steps), Delete or a double click removes it. Carries `data-blocked` briefly when removal is refused at `minPoints`. Renders a `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `getAriaValueText` | `(point: GeomPoint, index: number) => string` | | Returns the point's `aria-valuetext`. Defaults to the formatted `x, y`. | | `index` | `number` | | Index of the point in the (sorted) value. | **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-dragging` | Whether a point is being dragged. | | `data-blocked` | Briefly true after a removal was refused at `minPoints`. | | `data-removable` | Whether the point can currently be removed. | ### Registry component `Envelope` accepts style props (`size`, `className`) plus primitive props from `EnvelopePrimitive.Root.Props`. `aria-label` / `aria-labelledby` name the envelope group. #### Value and state | Prop | Type | Default | Description | | --- | --- | --- | --- | | `value` | `{ x: number; y: number; curve?: number }[]` | | Controlled points, normalized 0-1, sorted by `x`. `curve`, -1 to 1, bends the segment leaving the point. | | `defaultValue` | `{ x: number; y: number; curve?: number }[]` | `ADSR-like 5-point shape` | Uncontrolled starting points. Defaults to an ADSR-like shape. | | `minPoints` | `number` | `2` | Floor on the number of points; removal is blocked at this count. | | `maxPoints` | `number` | | Ceiling on the number of points; adding is blocked at this count. Equal to `minPoints`, the shape is fixed. | | `step` | `number` | `0.01` | Keyboard step on both axes, in normalized units. | | `disabled` | `boolean` | `false` | Whether the envelope is disabled. | | `format` | `Intl.NumberFormatOptions` | | Formats point coordinates for each point's `aria-valuetext`. | | `onValueChange` | `(points, eventDetails) => void` | | Fires on every change: drag, keyboard, add and remove. | | `onValueCommitted` | `(points, eventDetails) => void` | | Fires when an interaction that changed the points ends. | #### Layout and display | Prop | Type | Default | Description | | --- | --- | --- | --- | | `size` | `"sm" \| "default" \| "lg"` | `"default"` | Size variant (sets the envelope height). | | `curves` | `boolean` | `true` | Whether a handle on each segment bends it. | | `formatValue` | `(point: { x: number; y: number }) => string` | `from the domains` | Prints a point's value in its label and its accessible value text. | | `xDomain / yDomain` | `[number, number]` | `percent` | The values each axis runs from and to, so the labels read in real units: `xDomain={[0, 2000]}`. | | `xUnit / yUnit` | `string` | | The unit written after the value, such as `"ms"` or `"dB"`. | | `className` | `string` | | Classes for the graph surface. | `@audio-ui/react/envelope` exposes `Envelope.Root`, `Envelope.Graph` (the SVG surface; double-click to add), `Envelope.Line` and `Envelope.Fill` (the curve and the area under it), `Envelope.Points` (renders one child per point), `Envelope.Point` (the draggable handle), `Envelope.Segments` (renders one child per segment) and `Envelope.Segment` (the handle on a segment's midpoint, which bends it). Every part accepts a `render` prop and `className` / `style` as functions of state; points expose `data-dragging`, `data-removable`, `data-blocked`, `data-disabled` and `data-index`, and segment handles `data-dragging`, `data-flat` and `data-disabled`. ## Examples ### ADSR with its stages read out ```tsx "use client"; import { useState } from "react"; import { Envelope } from "@/components/audio-ui/envelope"; /** The span the envelope's x axis stands for, in milliseconds. */ const SPAN_MS = 2000; const INITIAL_POINTS = [ { x: 0, y: 0 }, { x: 0.08, y: 1 }, { x: 0.28, y: 0.6 }, { x: 0.72, y: 0.6 }, { x: 1, y: 0 }, ]; const toMs = (share: number) => `${Math.round(share * SPAN_MS)} ms`; /** * An ADSR from five points: the second is the end of the attack, the third * the end of the decay, and the fourth the start of the release. The * consumer maps the normalized axes to its own units, here milliseconds * and a level. */ export function EnvelopeAdsrDemo() { const [points, setPoints] = useState(INITIAL_POINTS); const [, peak, decayEnd, releaseStart] = points; return (
{peak && decayEnd && releaseStart ? (
Attack
{toMs(peak.x)}
Decay
{toMs(decayEnd.x - peak.x)}
Sustain
{Math.round(decayEnd.y * 100)}%
Release
{toMs(1 - releaseStart.x)}
) : null}
); } ``` --- # Fader > A linear slider for gain and other continuous parameters. ```tsx import { Fader } from "@/components/audio-ui/fader"; const MARKS = [ { label: "0", value: 0 }, 25, 50, 75, { label: "100", value: 100 }, ]; export function FaderVerticalDemo() { return ( ); } ``` A linear control for continuous parameters such as volume, gain or a send level. The registry component wraps the `Fader` primitive from `@audio-ui/react` and adds size variants and thumb marks. ## Overview - **Input:** drag the thumb or press the track, or use the mouse wheel or the keyboard. `onValueCommitted` fires when the interaction ends. - **Layout:** vertical by default, or horizontal, in `sm`, `default` and `lg` sizes. - **Display:** a filled range and a thumb, with optional marks inside the thumb (`thumbMarks`). - **Accessibility:** the thumb holds a native `` that carries the accessible name (`aria-label` or `aria-labelledby`), the value text (formatted with `format`) and the form value (`name`). ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/fader ``` **Manual** **1. Install the following dependencies:** ```bash npm install @audio-ui/react class-variance-authority ``` **2. Copy and paste the following code into your project.** ```tsx title="components/audio-ui/fader.tsx" "use client"; import { Fader as FaderPrimitive } from "@audio-ui/react"; import { cva, type VariantProps } from "class-variance-authority"; import type { ReactNode } from "react"; import { cn } from "@/lib/utils"; const faderVariants = cva("", { defaultVariants: { size: "default", }, variants: { size: { default: "", lg: "", sm: "", }, }, }); const faderTrackVariants = cva( "rounded-full bg-input/90 relative grow cursor-pointer select-none overflow-hidden", { defaultVariants: { size: "default", }, variants: { size: { default: "data-[orientation=horizontal]:h-2 data-[orientation=vertical]:h-full data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-2", lg: "data-[orientation=horizontal]:h-2.5 data-[orientation=vertical]:h-full data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-2.5", sm: "data-[orientation=horizontal]:h-1.5 data-[orientation=vertical]:h-full data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-1.5", }, }, } ); const faderThumbVariants = cva( "border-ring border bg-card transition-[color,box-shadow] hover:ring-2 hover:ring-ring/40 has-focus-visible:ring-3 has-focus-visible:ring-ring/50 active:ring-3 active:ring-ring/50 motion-reduce:transition-none before:-inset-2 absolute z-10 block shrink-0 cursor-grab select-none outline-none before:absolute before:content-[''] active:cursor-grabbing data-disabled:pointer-events-none", { defaultVariants: { size: "default", }, variants: { size: { default: "rounded-[min(var(--radius-md),10px)] data-[orientation=horizontal]:h-4 data-[orientation=vertical]:h-6 data-[orientation=horizontal]:w-6 data-[orientation=vertical]:w-4", lg: "rounded-[min(var(--radius-lg),12px)] data-[orientation=horizontal]:h-5 data-[orientation=vertical]:h-7 data-[orientation=horizontal]:w-7 data-[orientation=vertical]:w-5", sm: "rounded-[min(var(--radius-sm),8px)] data-[orientation=horizontal]:h-3.5 data-[orientation=vertical]:h-5 data-[orientation=horizontal]:w-5 data-[orientation=vertical]:w-3.5", }, }, } ); const faderThumbInnerVariants = cva( "flex h-full w-full items-center justify-center gap-0.5 data-[orientation=horizontal]:flex-row data-[orientation=vertical]:flex-col", { defaultVariants: { size: "default", }, variants: { size: { default: "data-[orientation=horizontal]:px-1.5 data-[orientation=horizontal]:py-1 data-[orientation=vertical]:px-1 data-[orientation=vertical]:py-1.5", lg: "data-[orientation=horizontal]:px-2 data-[orientation=horizontal]:py-1 data-[orientation=vertical]:px-1 data-[orientation=vertical]:py-2", sm: "data-[orientation=horizontal]:px-1 data-[orientation=horizontal]:py-0.5 data-[orientation=vertical]:px-0.5 data-[orientation=vertical]:py-1", }, }, } ); const faderThumbMarkVariants = cva("bg-primary opacity-50", { defaultVariants: { size: "default", }, variants: { size: { default: "data-[orientation=horizontal]:h-2.5 data-[orientation=vertical]:h-px data-[orientation=horizontal]:w-px data-[orientation=vertical]:w-2.5", lg: "data-[orientation=horizontal]:h-3 data-[orientation=vertical]:h-px data-[orientation=horizontal]:w-px data-[orientation=vertical]:w-3", sm: "data-[orientation=horizontal]:h-2.5 data-[orientation=vertical]:h-px data-[orientation=horizontal]:w-px data-[orientation=vertical]:w-2.5", }, }, }); /** A graduation on the fader's scale: a value, or a value and its label. */ export type FaderMark = number | { label?: ReactNode; value: number }; interface FaderProps extends FaderPrimitive.Root.Props, VariantProps { /** Lets you type the value: a double click on the readout, or Enter while it has focus. */ editableValue?: boolean; /** Prints the value in the readout and in what screen readers announce, e.g. as `"-6 dB"`. Defaults to `format`/`locale`. */ formatValue?: (value: number) => string; /** Graduations drawn beside the track: a ruler for the value. */ marks?: readonly FaderMark[]; thumbMarks?: number | false; /** When the value shows beside the thumb: while hovered, dragged or focused (`auto`), `always`, or `hidden`. */ valueLabel?: "always" | "auto" | "hidden"; } const markValue = (mark: FaderMark) => typeof mark === "number" ? mark : mark.value; const markLabel = (mark: FaderMark) => typeof mark === "number" ? undefined : mark.label; export function Fader({ "aria-describedby": ariaDescribedBy, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, className, editableValue = false, formatValue, marks, size, orientation = "vertical", thumbMarks = 3, valueLabel = "auto", ...props }: FaderProps) { const hasLabels = marks?.some((mark) => markLabel(mark) !== undefined); return ( {marks ? ( ) : null} formatValue(value) : undefined } >
{thumbMarks !== false && Array.from({ length: thumbMarks }, (_, i) => (
))}
{valueLabel === "hidden" ? null : ( {(formatted, values) => formatValue && values[0] !== undefined ? formatValue(values[0]) : formatted[0] } )} ); } ``` **3. Update the import paths to match your project setup.** **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the fader from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Anatomy Import the primitive and assemble its parts. ```tsx import { Fader } from "@audio-ui/react"; ``` ## Usage ```tsx import { Fader } from "@/components/audio-ui/fader"; ``` **Uncontrolled:** set only the initial value. ```tsx ``` **Controlled:** drive the value from state. ```tsx const [gain, setGain] = useState(0); console.log("Committed:", value, details.reason)} step={1} value={gain} /> ``` ## Interaction ### Pointer **Behavior** | Gesture | Effect | | --- | --- | | Track click / drag | Click or drag on the track to set the value from the pointer position. | | Thumb drag | Dragging the thumb changes the value continuously, within `min…max`. | | Commit event | `onValueCommitted` fires when an interaction ends with a new value. | | Lagging value | While dragging, the thumb follows the pointer even if a controlled `value` updates late; it returns to `value` on release. Reject a value with `eventDetails.cancel()`. | ### Keyboard On the focused thumb: **Keys** | Key | Effect | | --- | --- | | `ArrowUp` / `ArrowRight` | Increase by `step` | | `ArrowDown` / `ArrowLeft` | Decrease by `step` | | `PageUp` / `Shift` + `ArrowUp` | Increase by `largeStep` (default `10`) | | `PageDown` / `Shift` + `ArrowDown` | Decrease by `largeStep` (default `10`) | | `Home` | Set to `min` | | `End` | Set to `max` | ### Wheel The mouse wheel over the fader moves the value by `step` and reports `eventDetails.reason === "wheel"`. ## API reference ### Root Groups all parts of the fader, with audio defaults (vertical, -60…+6) and mouse-wheel stepping. While a pointer drags it, the thumb follows the pointer even if a controlled `value` lags behind, as with a seek bar driven by playback time or automation. To reject a value, call `eventDetails.cancel()`. Renders a `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `anchor` | `number` | | Value the `Indicator` fills from, such as `0` on a -1…1 pan. Defaults to `min`. | | `defaultValue` | `number` | | Uncontrolled starting value, and what a double click, an Alt + click or the Delete key return to; defaults to the midpoint of `min…max`. | | `max` | `number` | `6` | | | `min` | `number` | `-60` | | | `onValueChange` | `(value: number, eventDetails: ChangeEventDetails) => void` | | Fires on drag, track press, keyboard, wheel and form input changes. | | `onValueCommitted` | `(value: number, eventDetails: CommitEventDetails) => void` | | Fires when an interaction ends with a new value. | | `orientation` | `"horizontal" \| "vertical"` | `"vertical"` | | | `value` | `number` | | | **Data attributes** | Attribute | Description | | --- | --- | | `data-active` | Whether the value has reached this mark from the anchor. | | `data-disabled` | Present when disabled. | ### Control The interactive area: pointer presses and drags, plus mouse-wheel stepping. Sets `touch-action: none` so touch drags don't scroll the page. Renders a `
` element. **Data attributes** | Attribute | Description | | --- | --- | | `data-active` | Whether the value has reached this mark from the anchor. | | `data-disabled` | Present when disabled. | ### Indicator The filled part of the track: from `min` up to the value, or between the Root's `anchor` and the value, on whichever side of it the value is. Renders a `
` element. **Data attributes** | Attribute | Description | | --- | --- | | `data-active` | Whether the value has reached this mark from the anchor. | | `data-disabled` | Present when disabled. | ### Mark A graduation along the track at `value`: placed from the start of the travel in the fader's direction, where the thumb's center would be at that value. It carries `data-active` while the value has reached it from the anchor, and `data-orientation`. Decorative: the thumb's input announces the value. Render your own tick and label inside it. Renders a `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `value` | `number` | | Where the mark sits, between `min` and `max`. | **Data attributes** | Attribute | Description | | --- | --- | | `data-active` | Whether the value has reached this mark from the anchor. | | `data-disabled` | Present when disabled. | ### Registry component `Fader` accepts style props (`size`, `thumbMarks`, `className`) plus primitive props from `FaderPrimitive.Root.Props` (`name`, `form`, `format`, `locale`, `largeStep`, `render`, …). The primitive's `Fader.Mark` places a graduation at a `value` along the track, with `data-active` once the value has reached it, to build your own ruler. `aria-label`, `aria-labelledby`, and `aria-describedby` are forwarded to the thumb's input. #### Value and state | Prop | Type | Default | Description | | --- | --- | --- | --- | | `value` | `number` | | Where the mark sits, between `min` and `max`. | | `defaultValue` | `number` | `midpoint` | Uncontrolled starting value, and what a double click, an Alt + click or the Delete key return to; defaults to the midpoint of `min…max`. | | `min` | `number` | `-60` | Minimum value. | | `max` | `number` | `6` | Maximum value. | | `step` | `number` | `1` | Granularity of every change. | | `marks` | `(number \| { value, label? })[]` | | Graduations drawn beside the track: a ruler for the value. Those the value has reached from `anchor` light up. | | `valueLabel` | `"auto" \| "always" \| "hidden"` | `"auto"` | When the value shows beside the thumb: `auto` while hovered, dragged or focused from the keyboard. | | `formatValue` | `(value: number) => string` | `format` | How the value prints in that readout and in what screen readers announce, e.g. `"-6.0 dB"`. | | `editableValue` | `boolean` | `false` | Lets you type the value in the readout: a double click, or Enter while it has focus. Enter commits it, Escape drops it (`reason: "input-change"`). | | `anchor` | `number` | `min` | Value the `Indicator` fills from, such as `0` on a -1…1 pan. Defaults to `min`. | | `disabled` | `boolean` | `false` | Disables interaction. | | `onValueChange` | `(value: number, eventDetails) => void` | | Fires on drag, track press, keyboard, wheel and form input changes. | | `onValueCommitted` | `(value: number, eventDetails) => void` | | Fires when an interaction ends with a new value. | | `aria-label` | `string` | | Accessible name for the slider. | | `aria-labelledby` | `string` | | ID of a labeling element. | #### Layout and visuals | Prop | Type | Default | Description | | --- | --- | --- | --- | | `orientation` | `"horizontal" \| "vertical"` | `"vertical"` | Direction of travel. | | `size` | `"sm" \| "default" \| "lg"` | `"default"` | Track and thumb size preset. | | `thumbMarks` | `number \| false` | `3` | Number of marks in the thumb or `false` to hide them. | | `className` | `string` | | Root wrapper class name. | Additional valid HTML attributes passed to `Fader.Root` are forwarded. A vertical fader takes the height it is given, and never less than `--fader-min-height` (10rem by default). Set it lower where room is short, such as a mixer on a small screen: `[--fader-min-height:5rem]` on a parent. ## Examples ### Vertical (default) ```tsx import { Fader } from "@/components/audio-ui/fader"; const MARKS = [ { label: "0", value: 0 }, 25, 50, 75, { label: "100", value: 100 }, ]; export function FaderVerticalDemo() { return ( ); } ``` ### Pan, filled from the center `anchor={0}` makes the fill grow from the center of a -1…1 range, left or right of it. ```tsx "use client"; import { useState } from "react"; import { Fader } from "@/components/audio-ui/fader"; const formatPan = (pan: number) => { const amount = Math.round(Math.abs(pan) * 100); if (amount === 0) { return "C"; } return `${pan < 0 ? "L" : "R"}${amount}`; }; export function FaderPanDemo() { const [pan, setPan] = useState(-0.3); return (
{formatPan(pan)}
); } ``` ### Mixing console A fader per channel in dB, from silent at the bottom to +6 dB, beside the meter of what it lets through. ```tsx "use client"; 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 { usePlaySwitch } from "@/hooks/use-play-switch"; import { useTrackAutomation } from "@/hooks/use-track-automation"; 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(null); // The sounds, as the tracks' recordings, and a clip on each that loops it. const [sources, setSources] = useState>( () => 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 (
); } ``` --- # Knob > A rotary control for continuous parameters, with pointer, wheel and keyboard input. ```tsx import { Knob } from "@/components/audio-ui/knob"; const MARKS = [ { label: "0", value: 0 }, 25, 50, 75, { label: "100", value: 100 }, ]; export function KnobDemo() { return ( ); } ``` A rotary control for continuous parameters such as level, cutoff or pan. The registry component wraps the `Knob` primitive from `@audio-ui/react` and adds size variants and theme styles. ## Overview - **Input:** drag around the knob (`dragMode="circular"`, the default), up and down (`"vertical"`), or by full turns (`"revolution"`). The mouse wheel and the keyboard also work. A double-click or a double-tap returns to `defaultValue`. - **Display:** a track, an arc from `anchor` to the value, and a needle that turns with the value. The needle follows the pointer without easing, so it stays in line with the arc. - **Accessibility:** the knob holds a native `` that takes focus and carries the accessible name (`aria-label` or `aria-labelledby`), the value text (formatted with `format`, or set with `getAriaValueText` on the primitive's `Thumb`) and the form value (`name`). ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/knob ``` **Manual** **1. Install the following dependencies:** ```bash npm install @audio-ui/react class-variance-authority ``` **2. Copy and paste the following code into your project.** ```tsx title="components/audio-ui/knob.tsx" "use client"; import { Knob as KnobPrimitive } from "@audio-ui/react"; import { cva, type VariantProps } from "class-variance-authority"; import type { ReactNode } from "react"; import { cn } from "@/lib/utils"; const knobVariants = cva( "rounded-full border border-transparent ring-1 ring-foreground/10 transition-[border-color,box-shadow] duration-150 ease-out focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 hover:ring-2 hover:ring-ring/40 has-[[data-slot=knob-control]:active]:border-ring has-[[data-slot=knob-control]:active]:ring-3 has-[[data-slot=knob-control]:active]:ring-ring motion-reduce:transition-none relative inline-flex outline-none data-disabled:cursor-not-allowed", { defaultVariants: { size: "default", }, variants: { size: { default: "size-12", lg: "size-16", sm: "size-11", xl: "size-24", xs: "size-8", }, }, } ); const knobControlClassName = "bg-secondary text-secondary-foreground shadow-xs transition-[color,background-color,box-shadow,border-color,opacity] duration-150 ease-out hover:bg-secondary/90 active:shadow-[inset_0_-14px_28px_-12px_rgb(0_0_0/0.14)] motion-reduce:transition-none dark:bg-secondary/60 dark:hover:bg-secondary/70 dark:active:shadow-[inset_0_-14px_28px_-12px_rgb(0_0_0/0.28)] transform-[translateZ(0)] relative isolate flex size-full cursor-grab touch-none select-none outline-none [clip-path:circle(50%_at_50%_50%)] focus-visible:outline-none active:cursor-grabbing data-disabled:pointer-events-none data-disabled:opacity-50"; const knobBodyVariants = cva("rounded-full bg-card text-card-foreground ring-1 ring-foreground/10 transition-transform duration-100 ease-out motion-reduce:transition-none absolute z-0", { defaultVariants: { size: "default", }, variants: { size: { default: "inset-1.5", lg: "inset-2", sm: "inset-1", xl: "inset-2.5", xs: "inset-1", }, }, }); /** A graduation around the dial: a value, or a value and its label. */ export type KnobMark = number | { label?: ReactNode; value: number }; export type KnobProps = KnobPrimitive.Root.Props & VariantProps & { /** Prints the value in the readout and in what screen readers announce, e.g. as `"8.7 kHz"`. Defaults to `format`/`locale`. */ formatValue?: (value: number) => string; /** Graduations drawn around the dial, on its scale. */ marks?: readonly KnobMark[]; /** Lets you type the value: a double click on the readout, or Enter while it has focus. */ editableValue?: boolean; /** When the value shows under the dial: while hovered, turned or focused (`auto`), `always`, or `hidden`. */ valueLabel?: "always" | "auto" | "hidden"; }; const markValue = (mark: KnobMark) => typeof mark === "number" ? mark : mark.value; const markLabel = (mark: KnobMark) => typeof mark === "number" ? undefined : mark.label; function Knob({ "aria-describedby": ariaDescribedBy, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, className, dragMode, editableValue = false, formatValue, marks, size, valueLabel = "auto", ...props }: KnobProps) { const hasLabels = marks?.some((mark) => markLabel(mark) !== undefined); return (
formatValue(value) : undefined } > {marks?.map((mark) => ( {markLabel(mark) === undefined ? null : ( {markLabel(mark)} )} ))} {valueLabel === "hidden" ? null : ( {(formatted, value) => (formatValue ? formatValue(value) : formatted)} )} ); } export { Knob, knobVariants }; ``` **3. Update the import paths to match your project setup.** **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the knob from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Anatomy Import the primitive and assemble its parts. ```tsx import { Knob } from "@audio-ui/react"; ``` ## Usage ```tsx import { Knob } from "@/components/audio-ui/knob"; ``` **Uncontrolled:** set only the initial value. ```tsx ``` **Controlled:** drive the value from state. ```tsx const [cutoff, setCutoff] = useState(1000); ``` Pass `defaultValue` even when the knob is controlled if you use the double-tap reset: it sets the value the knob returns to, clamped and stepped. ## Interaction ### Pointer **Behavior** | Gesture | Effect | | --- | --- | | Circular drag (default) | The value follows the rotation around the center, from the value at pointer down. The dial's 288° sweep spans `min…max`. | | Vertical drag | `dragMode="vertical"`: drag up to increase, like a fader; 150px of travel spans `min…max`. | | Revolution drag | `dragMode="revolution"`: one full 360° turn spans `min…max`. | | Fine drag | Hold `Shift` while dragging, in any mode, to turn four times slower. Only the stretch moved with `Shift` held is slowed, and small moves add up rather than rounding away. | | Double-tap / double-click | Two quick taps (each moving ≤ ~12px, within ~320ms) reset to `defaultValue`, or to the middle of the dial's travel without one. Reports `eventDetails.reason === "reset"`. | Values stay within `min…max` and do not wrap. While dragging, the knob follows the pointer even if a controlled `value` updates late. ### Scale `scale` sets how the value maps onto the dial's travel. `"linear"` (the default) suits levels and times; `"log"` suits frequency, resonance and ratios, which are heard as proportions: on a 20 Hz–20 kHz cutoff, every decade gets the same share of the dial, and 632 Hz sits at the middle. A log scale needs a positive `min`. For anything else, pass your own `{ toPosition, toValue }`, mapping a value to 0…1 along the travel and back. ```tsx ``` Away from linear, the keys and the wheel move a share of the travel (1%, or 10% with `Shift` and the Page keys) rather than a `step`, and always by at least one `step`. ### Keyboard On the focused knob: **Keys** | Key | Effect | | --- | --- | | `ArrowUp` / `ArrowRight` | Increase by `step` | | `ArrowDown` / `ArrowLeft` | Decrease by `step` | | `PageUp` / `Shift` + `ArrowUp` | Increase by `largeStep` (default `10`) | | `PageDown` / `Shift` + `ArrowDown` | Decrease by `largeStep` (default `10`) | | `Home` | Set to `min` | | `End` | Set to `max` | ### Wheel The mouse wheel over the knob moves the value by `step` and reports `eventDetails.reason === "wheel"`. ## API reference ### Root Groups all parts of the knob and owns its value. Dragging the `Control`, turning the mouse wheel over it, the keyboard on the `Thumb`'s input, or a double tap (reset) all report through `onValueChange` / `onValueCommitted`. Renders a `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `anchor` | `number` | | Value the indicator arc grows from (e.g. `0` on a -1…1 pan knob). Defaults to `min`. | | `defaultValue` | `number` | | Uncontrolled starting value, and the reset target of a double tap, an Alt + click and the Delete key. Defaults to the middle of the dial's travel. | | `disabled` | `boolean` | | | | `dragMode` | `DragMode` | `"circular"` | | | `form` | `string` | | Identifies the form that owns the knob's input, when rendered outside it. | | `format` | `Intl.NumberFormatOptions` | | Formats the value for `Knob.Value` and the input's `aria-valuetext`. | | `largeStep` | `number` | `10` | Step for Page Up/Page Down and Shift + Arrow keys. | | `locale` | `Intl.LocalesArgument` | | | | `max` | `number` | `100` | | | `min` | `number` | `0` | | | `name` | `string` | | Identifies the field when a form is submitted. | | `onValueChange` | `(value: number, eventDetails: ChangeEventDetails) => void` | | Fires on every change: drag, keyboard, wheel, reset and input changes. | | `onValueCommitted` | `(value: number, eventDetails: CommitEventDetails) => void` | | Fires when an interaction ends with a new value. | | `scale` | `Scale` | `"linear"` | How the value maps onto the dial's travel: `linear`, `log` for frequency, Q or ratios (needs a positive `min`), or your own `{ toPosition, toValue }`. Away from linear, the keys and the wheel move a share of the travel (1%, or 10% with Shift and Page keys) rather than a `step`. | | `step` | `number` | `1` | | | `value` | `number` | | | **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-drag-mode` | The `dragMode`: `circular`, `revolution` or `vertical`. Style the cursor from it. | | `data-dragging` | Whether a pointer is dragging the knob. | ### Control The interactive surface: pointer drags (see `dragMode`), mouse-wheel stepping, and double tap to reset. Sets `touch-action: none` so touch drags don't scroll the page. Renders a `
` element. **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-drag-mode` | The `dragMode`: `circular`, `revolution` or `vertical`. Style the cursor from it. | | `data-dragging` | Whether a pointer is dragging the knob. | ### Track The full sweep of the dial, as an SVG arc. Renders a `` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `strokeWidth` | `number` | `3` | Stroke width in the 48×48 viewBox; the arc stays inside the box. | **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-drag-mode` | The `dragMode`: `circular`, `revolution` or `vertical`. Style the cursor from it. | | `data-dragging` | Whether a pointer is dragging the knob. | ### Indicator The arc from `anchor` to the value, drawn over the `Track`. Renders a `` element. **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-drag-mode` | The `dragMode`: `circular`, `revolution` or `vertical`. Style the cursor from it. | | `data-dragging` | Whether a pointer is dragging the knob. | ### Thumb Rotates with the value (`rotate`, clockwise from 12 o'clock), so a pointer drawn inside it points at the value. Holds the knob's native `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `getAriaValueText` | `(formattedValue: string, value: number) => string` | | Returns the input's `aria-valuetext`, e.g. `"-6 dB"`. Defaults to the formatted value. | | `inputRef` | `React.Ref` | | | **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-drag-mode` | The `dragMode`: `circular`, `revolution` or `vertical`. Style the cursor from it. | | `data-dragging` | Whether a pointer is dragging the knob. | ### Value The formatted value (`format`/`locale` on Root). With `editable`, a double click, or Enter while it has focus, lets you type a value: Enter commits it (a unit or a decimal comma is fine, and it is clamped), Escape drops it, and it reports `reason: "input-change"`. Renders a `` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `children` | `\| React.ReactNode \| ((formattedValue: string, value: number) => React.ReactNode)` | | | | `editable` | `boolean` | `false` | Allows typing a value: double-click, or press Enter while it has focus. | **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-drag-mode` | The `dragMode`: `circular`, `revolution` or `vertical`. Style the cursor from it. | | `data-dragging` | Whether a pointer is dragging the knob. | ### Mark A graduation on the dial at `value`, placed on the knob's scale: a layer the size of the knob, rotated to where `value` sits, so a tick drawn at its top lands on the sweep. Its `--knob-mark-angle` CSS variable is that rotation, to turn a label back upright. It carries `data-active` while the value has reached it from the anchor. Decorative: the input announces the value. Renders a `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `value` | `number` | | Where the mark sits, on the knob's scale. | **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-drag-mode` | The `dragMode`: `circular`, `revolution` or `vertical`. Style the cursor from it. | | `data-dragging` | Whether a pointer is dragging the knob. | | `data-active` | Whether the value has reached this mark from the anchor. | ### Label Accessible label, associated with the thumb's input. Renders a `
` element. **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | | `data-drag-mode` | The `dragMode`: `circular`, `revolution` or `vertical`. Style the cursor from it. | | `data-dragging` | Whether a pointer is dragging the knob. | ### Provider Sets how every `Knob.Root` below it turns by a drag, unless the knob has a `dragMode` of its own: wrap an app once to have all its knobs dragged up and down. Renders no element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `dragMode` | `"circular" \| "vertical" \| "revolution"` | | How a pointer drag turns into value, for the knobs that do not set their own. | ### Registry component `Knob` accepts `size` and `className` plus primitive props from `KnobPrimitive.Root.Props`. `aria-label`, `aria-labelledby`, and `aria-describedby` are forwarded to the knob's input. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `value` | `number` | | Where the mark sits, on the knob's scale. | | `defaultValue` | `number` | `middle of the travel` | Uncontrolled starting value, and the reset target of a double tap, an Alt + click and the Delete key. Defaults to the middle of the dial's travel. | | `min` | `number` | `0` | Minimum. | | `max` | `number` | `100` | Maximum. | | `step` | `number` | `1` | Quantization step (drag, wheel, keyboard, reset). | | `largeStep` | `number` | `10` | Step for Page Up/Page Down and Shift + Arrow keys. | | `anchor` | `number` | `min` | Value the indicator arc grows from (e.g. `0` on a -1…1 pan knob). Defaults to `min`. | | `dragMode` | `"circular" \| "vertical" \| "revolution"` | `"circular"` | How pointer travel turns into value. | | `scale` | `"linear" \| "log" \| { toPosition, toValue }` | `"linear"` | How the value maps onto the dial's travel. | | `marks` | `(number \| { value, label? })[]` | | Graduations drawn around the dial, on its scale. Those the value has reached from `anchor` light up. | | `valueLabel` | `"auto" \| "always" \| "hidden"` | `"auto"` | When the value shows under the dial: `auto` while hovered, turned or focused from the keyboard. | | `formatValue` | `(value: number) => string` | `format` | How the value prints in that readout and in what screen readers announce, e.g. `"8.7 kHz"`. | | `editableValue` | `boolean` | `false` | Lets you type the value in the readout: a double click, or Enter while it has focus. | | `disabled` | `boolean` | `false` | Disables pointer, wheel, and keyboard. | | `format` | `Intl.NumberFormatOptions` | | Formats the value for `Knob.Value` and the input's `aria-valuetext`. | | `locale` | `Intl.LocalesArgument` | `runtime` | Locale used by `format`. | | `name` | `string` | | Identifies the field when a form is submitted. | | `onValueChange` | `(value: number, eventDetails) => void` | | Fires on every change: drag, keyboard, wheel, reset and input changes. | | `onValueCommitted` | `(value: number, eventDetails) => void` | | Fires when an interaction ends with a new value. | | `size` | `"xs" \| "sm" \| "default" \| "lg" \| "xl"` | `"default"` | Diameter variant. | | `className` | `string` | | On the root wrapper. | `@audio-ui/react/knob` exposes `Knob.Root`, `Knob.Control` (pointer, wheel, reset), `Knob.Track` and `Knob.Indicator` (SVG arcs; `strokeWidth` in the 48×48 viewBox), `Knob.Thumb` (rotates with the value and holds the input), `Knob.Value` (formatted ``), `Knob.Provider` (the default `dragMode` of the knobs below it), `Knob.Mark` (a graduation at a `value`, rotated onto the dial's scale, with `data-active` once reached), and `Knob.Label`. Every part accepts a `render` prop, `className` / `style` as functions of state, and exposes `data-disabled` / `data-dragging`. ## Examples ### Rail, anchor, and range highlight Use `anchor` to show a reference point on the rail (for example the center of a bipolar control). The arc highlights the interval between `anchor` and the current value. ### Logarithmic scale `scale="log"` spreads a frequency evenly by ratio, so a quarter turn goes from 1 kHz to 8.7 kHz instead of packing the useful range into the first few degrees. ```tsx "use client"; import { useState } from "react"; import { Knob } from "@/components/audio-ui/knob"; const formatHertz = (hertz: number) => hertz >= 1000 ? `${(hertz / 1000).toFixed(1)} kHz` : `${hertz} Hz`; export function KnobFilterControlDemo() { const [cutoff, setCutoff] = useState(1000); return (
{formatHertz(cutoff)}
); } ``` ### Vertical drag `dragMode="vertical"` turns the knob like a fader: drag up to increase, down to decrease, with 150px of travel for the whole range. It suits a small knob, or one next to others, where going around it would be fiddly. To turn every knob of an app that way, wrap it once in `Knob.Provider`: each `Knob.Root` below it takes that mode, unless it sets its own `dragMode`. ```tsx import { Knob } from "@audio-ui/react" ``` --- # LCD > A small screen, as on a synth, that holds a reading under a caption, in light and dark alike. A small screen, as on a synth or a drum machine: the theme's foreground is its glass and its background the lit figures, so it reads as a screen in light and dark alike. It holds a reading, a `ValueDisplay` or a preset's name, under an optional caption. Its corners follow the style. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/lcd ``` **Manual** **1. Install the following dependencies:** ```bash npm install class-variance-authority ``` **2. Copy and paste the following code into your project.** ```tsx title="components/audio-ui/lcd.tsx" import { cva, type VariantProps } from "class-variance-authority"; import type { ReactNode } from "react"; import { cn } from "@/lib/utils"; const lcdVariants = cva("rounded-lg bg-foreground font-mono text-background tabular-nums shadow-[inset_0_1px_3px_rgb(0_0_0/0.45)] ring-1 ring-foreground/20 ring-inset inline-flex min-w-0 flex-col justify-center", { defaultVariants: { size: "default" }, variants: { /** "sm" for a single line in a dense panel. */ size: { default: "gap-0.5 px-3 py-2 text-sm", sm: "gap-0 px-2 py-1 text-xs", }, }, }); export interface LcdProps extends VariantProps { children: ReactNode; className?: string; /** A small caption over the reading: the parameter's or the preset's name. */ label?: ReactNode; /** Announces changes politely, for a reading that matters as it changes. @default false */ live?: boolean; } /** * A small screen, as on a synth or a drum machine: the theme's foreground as * its glass and its background as the lit figures, so it reads as a screen * in light and dark alike. Holds a reading (a `ValueDisplay`, a preset's * name) under an optional caption. */ export function Lcd({ children, className, label, live = false, size, }: LcdProps) { return (
{label ? ( {label} ) : null} {children}
); } ``` **3. Update the import paths to match your project setup.** **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the lcd from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Usage ```tsx import { Lcd } from "@/components/audio-ui/lcd"; 012 Warm Pad ``` For a value, put a [Value Display](/docs/components/base/value-display) in it, as the preview does: `` under the caption "Filter cutoff". Give it `live` when its reading matters as it changes: a screen readers announce politely. ## Together A synth's panel, with the screen showing the value last touched: Power plays an arpeggio at the tempo, through the waveform, the filter's cutoff and resonance, the gain and the transpose, into the master fader. ```tsx "use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { Fader } from "@/components/audio-ui/fader"; import { Knob } from "@/components/audio-ui/knob"; import { Lcd } from "@/components/audio-ui/lcd"; import { Led } from "@/components/audio-ui/led"; import { ParameterField } from "@/components/audio-ui/parameter-field"; import { RockerSwitch } from "@/components/audio-ui/rocker-switch"; import { ValueDisplay } from "@/components/audio-ui/value-display"; import { WaveformSelect } from "@/components/audio-ui/waveform-select"; import { useMasterBus } from "@/hooks/use-master-bus"; import { webAudio } from "@/lib/web-audio"; const WAVEFORMS = [ { label: "Sine", value: "sine" }, { label: "Triangle", value: "triangle" }, { label: "Sawtooth", value: "sawtooth" }, { label: "Square", value: "square" }, ] as const; /** The arpeggio, in semitones from C3: a minor seventh up and down. */ const STEPS = [0, 3, 7, 10, 12, 10, 7, 3] as const; const ROOT = 48; const SIGNED: Intl.NumberFormatOptions = { signDisplay: "exceptZero" }; /** How far ahead notes are scheduled, and how often the scheduler wakes, in seconds. */ const LOOKAHEAD = 0.1; const TICK_MS = 25; const hz = (note: number) => 440 * 2 ** ((note - 69) / 12); /** Which value the screen shows: the last one touched. */ type Shown = "cutoff" | "gain" | "resonance" | "tempo" | "transpose"; /** * A small synth's panel, every control of the audio set in one place: Power * plays an arpeggio at the tempo, through the oscillator's waveform, a * low-pass filter (cutoff and resonance), the gain and the transpose, into the * master fader. The screen shows the value last touched; the LED lights on * each beat. */ export function BlockSynthPanel() { const [power, setPower] = useState(false); const [bpm, setBpm] = useState(120); const [gain, setGain] = useState(-6); const [transpose, setTranspose] = useState(0); const [waveform, setWaveform] = useState("sawtooth"); const [cutoff, setCutoff] = useState(1800); const [resonance, setResonance] = useState(4); const [volume, setVolume] = useState(0.7); const [shown, setShown] = useState("cutoff"); const [beat, setBeat] = useState(false); const master = useMasterBus(volume); // What the scheduler reads as it goes, without restarting it. const live = useRef({ bpm, transpose, waveform }); live.current = { bpm, transpose, waveform }; const chain = useRef<{ filter: BiquadFilterNode; level: GainNode } | null>( null ); // The filter and the gain stage, made once the master bus is there. useEffect(() => { const ctx = webAudio.getContext(); if (!(ctx && master)) { return; } const filter = ctx.createBiquadFilter(); const level = ctx.createGain(); filter.type = "lowpass"; filter.connect(level).connect(master); chain.current = { filter, level }; return () => { level.disconnect(); filter.disconnect(); chain.current = null; }; }, [master]); useEffect(() => { const ctx = webAudio.getContext(); const nodes = chain.current; if (!(ctx && nodes)) { return; } nodes.filter.frequency.setTargetAtTime(cutoff, ctx.currentTime, 0.01); nodes.filter.Q.setTargetAtTime(resonance, ctx.currentTime, 0.01); nodes.level.gain.setTargetAtTime(10 ** (gain / 20), ctx.currentTime, 0.01); }, [cutoff, gain, resonance]); // The arpeggio, sixteenth notes at the tempo, scheduled a little ahead on the audio clock. useEffect(() => { const ctx = webAudio.getContext(); if (!(power && ctx && chain.current)) { return; } if (ctx.state !== "running") { ctx.resume(); } let step = 0; let next = ctx.currentTime + 0.05; const playNote = (at: number, note: number) => { const nodes = chain.current; if (!nodes) { return; } const length = 60 / live.current.bpm / 4; const oscillator = ctx.createOscillator(); const envelope = ctx.createGain(); oscillator.type = live.current.waveform as OscillatorType; oscillator.frequency.value = hz(note); envelope.gain.setValueAtTime(0, at); envelope.gain.linearRampToValueAtTime(0.25, at + 0.005); envelope.gain.setTargetAtTime(0, at + length * 0.6, 0.03); oscillator.connect(envelope).connect(nodes.filter); oscillator.start(at); oscillator.stop(at + length + 0.2); }; const timer = setInterval(() => { while (next < ctx.currentTime + LOOKAHEAD) { const index = step % STEPS.length; playNote(next, ROOT + (STEPS[index] ?? 0) + live.current.transpose); if (index % 4 === 0) { const delay = Math.max(0, (next - ctx.currentTime) * 1000); setTimeout(() => setBeat(true), delay); setTimeout(() => setBeat(false), delay + 90); } next += 60 / live.current.bpm / 4; step += 1; } }, TICK_MS); return () => { clearInterval(timer); setBeat(false); }; }, [power]); const showTempo = useCallback((value: number) => { setBpm(value); setShown("tempo"); }, []); const showGain = useCallback((value: number) => { setGain(value); setShown("gain"); }, []); const showTranspose = useCallback((value: number) => { setTranspose(value); setShown("transpose"); }, []); const showCutoff = useCallback((value: number) => { setCutoff(value); setShown("cutoff"); }, []); const showResonance = useCallback((value: number) => { setResonance(value); setShown("resonance"); }, []); const setMaster = useCallback( (value: number | readonly number[]) => setVolume(Array.isArray(value) ? (value[0] ?? 0) : Number(value)), [] ); const reading = { cutoff: , gain: , resonance: ( Q {resonance.toFixed(1)} ), tempo: , transpose: , }[shown]; return (
Power
{reading}
Cutoff
Reso
Master
); } ``` ## API reference | Prop | Type | Default | Description | | --- | --- | --- | --- | | `children` | `ReactNode` | | The reading. | | `label` | `ReactNode` | | A small caption over the reading: the parameter's or the preset's name. | | `live` | `boolean` | `false` | Announces changes politely, for a reading that matters as it changes. | | `size` | `"default" \| "sm"` | `"default"` | "sm" for a single line in a dense panel. | --- # LED > A status light that glows in its tone when lit, a dim dot when off, and blinks for an armed take. A status light, as on a panel: lit, it glows in its tone; off, it stays a dim dot, so its place still shows. It shows a state and sets none: put it beside the button or the switch that does. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/led ``` **Manual** **1. Install the following dependencies:** ```bash npm install class-variance-authority ``` **2. Copy and paste the following code into your project.** ```tsx title="components/audio-ui/led.tsx" import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const ledVariants = cva("rounded-full bg-muted-foreground/25 shadow-inner transition-[background-color,box-shadow] duration-100 data-on:bg-current data-on:shadow-[0_0_0.375rem_currentColor] data-blink:data-on:animate-pulse motion-reduce:transition-none motion-reduce:data-blink:data-on:animate-none inline-block shrink-0", { defaultVariants: { size: "default", tone: "primary", }, variants: { size: { default: "size-2", lg: "size-3", sm: "size-1.5", }, /** Its color when lit: the theme's primary, or destructive for recording and clipping. */ tone: { destructive: "text-destructive", primary: "text-primary", }, }, }); export interface LedProps extends VariantProps { /** Blinks while lit: a take arming, a clip about to start. Still for reduced motion. @default false */ blink?: boolean; className?: string; /** Names what it shows, for assistive technology: "Recording", "Signal". */ label: string; /** Whether it is lit. */ on: boolean; } /** * A status light: lit, it glows in its tone; off, a dim dot, so its place * still shows. It shows a state, it does not set one: its label reads the * state out ("Recording: on"). */ export function Led({ blink = false, className, label, on, size, tone, }: LedProps) { return ( ); } ``` **3. Update the import paths to match your project setup.** **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the led from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Usage ```tsx import { Led } from "@/components/audio-ui/led"; ``` Its label reads the state out to assistive technology ("Recording: on"). `blink` pulses it while lit, and holds it still for reduced motion. Its shape follows the style: round, or square in the square styles. ## API reference | Prop | Type | Default | Description | | --- | --- | --- | --- | | `on` | `boolean` | | Whether it is lit. | | `label` | `string` | | Names what it shows, for assistive technology: "Recording", "Signal". | | `tone` | `"primary" \| "destructive"` | `"primary"` | Its color when lit: the theme's primary, or destructive for recording and clipping. | | `blink` | `boolean` | `false` | Blinks while lit: a take arming, a clip about to start. Still for reduced motion. | | `size` | `"sm" \| "default" \| "lg"` | `"default"` | Its size. | --- # Meter > A level meter in decibels for one or more channels, with peak hold. ```tsx "use client"; 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 ( ); } ``` Shows audio levels for a stereo output, a channel strip or any multi-channel source. The registry component wraps the `Meter` primitive from `@audio-ui/react`: 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`](#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 **CLI** ```bash npx shadcn@latest add @audio-ui/meter ``` **Manual** **1. Install the following dependencies:** ```bash npm install @audio-ui/react class-variance-authority ``` **2. Copy and paste the following code into your project.** ```tsx title="components/audio-ui/meter.tsx" "use client"; import { Meter as MeterPrimitive } from "@audio-ui/react"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const meterVariants = cva("", { defaultVariants: { size: "default", }, variants: { size: { default: "data-[orientation=vertical]:h-48 data-[orientation=vertical]:[--meter-thickness:--spacing(3.5)] data-[orientation=horizontal]:[--meter-thickness:--spacing(3)]", lg: "data-[orientation=vertical]:h-64 data-[orientation=vertical]:[--meter-thickness:--spacing(4.5)] data-[orientation=horizontal]:[--meter-thickness:--spacing(4)]", sm: "data-[orientation=vertical]:h-32 data-[orientation=vertical]:[--meter-thickness:--spacing(2.5)] data-[orientation=horizontal]:[--meter-thickness:--spacing(2)]", }, }, }); interface MeterProps extends MeterPrimitive.Root.Props, VariantProps { /** Levels graduated along the meter's length, such as `[-48, -24, -12, -6, 0]`, each with its label. */ marks?: readonly number[]; peakMarks?: "visible" | "hidden"; } const decibels = (formattedValue: string) => `${formattedValue} dB`; export function Meter({ "aria-label": ariaLabel, className, marks, orientation = "vertical", scale = "iec", size, peakMarks = "visible", ...props }: MeterProps) { return ( {(index, channelCount) => ( 1 ? `${ariaLabel} ${index + 1}` : ariaLabel } className="rounded-[min(var(--radius-sm),6px)] bg-input/70 transition-shadow duration-150 ease-out data-clipping:ring-2 data-clipped:ring-2 data-clipping:ring-destructive data-clipped:ring-destructive relative flex-1 overflow-hidden data-[orientation=horizontal]:h-(--meter-thickness,auto) data-[orientation=horizontal]:flex-none data-[orientation=vertical]:w-(--meter-thickness,auto) data-[orientation=vertical]:flex-none" getAriaValueText={decibels} index={index} key={`meter-channel-${index}`} > {peakMarks === "visible" ? ( ) : null} )} {marks?.map((level) => ( ))} ); } ``` **3. Update the import paths to match your project setup.** **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the meter from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Anatomy Import the primitive and assemble its parts. ```tsx import { Meter } from "@audio-ui/react"; {(index) => ( )} ``` ## Usage ```tsx import { Meter } from "@/components/audio-ui/meter"; ``` **Static levels:** ```tsx ``` **With a peak-hold mark:** ```tsx ``` ## 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 `@audio-ui/react` 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); ; ``` 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/engine/analysis). To read the levels in React as well, for a numeric readout for example, use `useSyncExternalStore(levels.subscribe, levels.getSnapshot)`. ## API reference ### Root Groups the channels of a level meter. Levels come either from `value` (and `peak`) as React props, or from a live `source`: with a source the meter writes each frame straight to the DOM, so a signal updating 60 times a second never re-renders React. Renders a `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `clipThreshold` | `number` | `0` | Level at or above which a channel is clipping. | | `format` | `Intl.NumberFormatOptions` | | Formats each level for `Meter.Value` and the channels' `aria-valuetext`. Defaults to one decimal. | | `locale` | `Intl.LocalesArgument` | | | | `max` | `number` | `6` | | | `min` | `number` | `-60` | | | `orientation` | `Orientation` | `"vertical"` | | | `peak` | `readonly number[]` | | Peak-hold level per channel. Timing and decay live outside the primitive. | | `scale` | `"linear" \| "iec" \| (level: number) => number` | `"linear"` | How levels are spread along the length: evenly, as digital peak meters do with more room at the top (`"iec"`), or by your own increasing curve. | | `warnThreshold` | `number` | | Level at or above which a channel is in its warning zone, below the clip threshold: `data-warning`. Unset, there is no warning zone. | | `source` | `Source` | | A live signal painted outside React; takes precedence over `value` and `peak`. | | `value` | `readonly number[]` | | Level per channel; the array length is the channel count. | ### Channels Renders one child per channel. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `children` | `(index: number, channelCount: number) => React.ReactNode` | | | ### Channel One channel of the meter, a `role="meter"`: name it with `aria-label` or a `Meter.Label`. Carries `data-clipping` at or above the clip threshold. Renders a `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `getAriaValueText` | `(formattedValue: string, value: number, index: number) => string` | | Returns the channel's `aria-valuetext`, e.g. `"-6 dB"`. Defaults to the formatted level. | | `index` | `number` | | Index of the channel in the levels. | **Data attributes** | Attribute | Description | | --- | --- | | `data-clipping` | Whether the level is at or above the clip threshold. | ### Indicator The lit part of the channel, scaled to the level. Renders a `
` element. **Data attributes** | Attribute | Description | | --- | --- | | `data-clipping` | Whether the level is at or above the clip threshold. | ### Peak The peak-hold mark, positioned at the channel's peak level; hidden while the channel has none. Renders a `
` element. **Data attributes** | Attribute | Description | | --- | --- | | `data-clipping` | Whether the level is at or above the clip threshold. | ### Value The channel's formatted level (`format`/`locale` on Root). With a live `source` only the default text is kept current, not a `children` function. Renders a `` element. ### Mark A graduation of the level scale at `value`, such as -18 dB: placed along the meter's length from its minimum, upward for a vertical meter and rightward for a horizontal one. Sits directly in `Root`, beside the channels. Decorative: each channel announces its own level. Renders a `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `value` | `number` | | Where the mark sits, between `min` and `max`. | ### Registry component `Meter` accepts style props (`size`, `peakMarks`, `marks`, `className`) plus primitive props from `MeterPrimitive.Root.Props`. #### 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. | `@audio-ui/react/meter` exposes `Meter.Root` (the group), `Meter.Channels` (one child per channel), `Meter.Channel` (a `role="meter"`), `Meter.Track`, `Meter.Indicator` (the lit part), `Meter.Peak` (the peak-hold mark), `Meter.Value` (the formatted level) and `Meter.Label`. Channel parts expose `data-orientation` and `data-clipping`. ## Examples ### Mixing console Each channel's meter reads its real signal after the fader, and the master's reads both sides. ```tsx "use client"; 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 { usePlaySwitch } from "@/hooks/use-play-switch"; import { useTrackAutomation } from "@/hooks/use-track-automation"; 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(null); // The sounds, as the tracks' recordings, and a clip on each that loops it. const [sources, setSources] = useState>( () => 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 (
); } ``` ### 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`. --- # Needle meter > A VU meter to the standard, with its dial from -20 to +3 VU and a needle that moves the way a VU needle does. ```tsx "use client"; import { useMemo } from "react"; import { NeedleMeter } from "@/components/audio-ui/needle-meter"; import { useAudioLevels } from "@/hooks/use-audio-levels"; import { usePageMicrophone } from "@/hooks/use-microphone"; import { useSimulatedLevels } from "@/hooks/use-simulated-levels"; /** The needle follows the microphone when the bar's microphone is on, and a moving signal when it is not. */ export function NeedleMeterDemo() { const microphone = usePageMicrophone(); const heard = useAudioLevels( useMemo(() => (microphone ? [microphone] : []), [microphone]) ); // 0 VU is -18 dB: the levels stay between -15 and +3 VU, where the dial is. const simulated = useSimulatedLevels(1, { max: -15, min: -33 }); return ( ); } ``` A VU meter reads the level of a signal the way an engineer's ear does, as a slow average, not as peaks. The dial runs from -20 to +3 VU with the part above 0 VU in red, and the needle follows the first channel of a `source`. It is turned straight in the DOM on every frame, so the dial does not re-render with the signal. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/needle-meter ``` **Manual** **1. Install the following dependencies:** ```bash npm install @audio-ui/core ``` **2. Copy and paste the following code into your project.** ```tsx title="components/audio-ui/needle-meter.tsx" "use client"; import type { Source } from "@audio-ui/core"; import { createVuBallistics, FLOOR_DB, levelPosition, vuDeflection, } from "@audio-ui/core/meter"; import { useEffect, useRef } from "react"; import { cn } from "@/lib/utils"; /** The reading a needle meter follows: the levels of its channels, in dB. */ export interface NeedleMeterFrame { levels: readonly number[]; } /** The needle's travel, in degrees from the vertical: it rests at the left and ends at the right. */ const SWEEP = 70; const PIVOT_X = 100; const PIVOT_Y = 104; const RADIUS = 88; /** The marks of the standard VU scale, in VU: from -20 to +3, the part from 0 up in red. */ const MARKS = [-20, -10, -7, -5, -3, -2, -1, 0, 1, 2, 3] as const; const FIRST_MARK = -20; const LAST_MARK = 3; /** The fraction of the needle's travel at a level in VU: it follows the voltage, and rests at zero voltage. */ const position = levelPosition( vuDeflection, Number.NEGATIVE_INFINITY, LAST_MARK ); const sweepAt = (vu: number) => -SWEEP + position(vu) * 2 * SWEEP; /** The lean of the scale: the needle's travel starts at zero voltage, so the first mark is not as far from the left stop as the last is from the right one. */ const LEAN = (sweepAt(FIRST_MARK) + sweepAt(LAST_MARK)) / 2; /** The angle of a level, in degrees from the vertical, with the printed scale centered on it. */ const angleOf = (vu: number) => sweepAt(vu) - LEAN; const pointOn = (angle: number, radius: number) => { const radians = (angle * Math.PI) / 180; return { x: PIVOT_X + radius * Math.sin(radians), y: PIVOT_Y - radius * Math.cos(radians), }; }; const TICK_WIDTH = 1.5; const ARC_WIDTH = 1; const ZONE_WIDTH = 3; /** The angle half a tick takes along the outer edge of the marks. */ const TICK_MARGIN = ((TICK_WIDTH / 2 / RADIUS) * 180) / Math.PI; /** An arc between two angles along the outer edge of the marks, `width` thick and inside that edge. */ const arcBetween = (from: number, to: number, width: number) => { const radius = RADIUS - width / 2; const start = pointOn(from, radius); const end = pointOn(to, radius); return `M ${start.x} ${start.y} A ${radius} ${radius} 0 0 1 ${end.x} ${end.y}`; }; const SCALE = MARKS.map((mark) => { const angle = angleOf(mark); return { hot: mark > 0, inner: pointOn(angle, RADIUS - 8), label: mark > 0 ? `+${mark}` : String(Math.abs(mark)), mark, outer: pointOn(angle, RADIUS), text: pointOn(angle, RADIUS + 10), }; }); // The scale line and the red band run half a tick past their end marks, so no tick sticks out. const SCALE_ARC = arcBetween( angleOf(FIRST_MARK) - TICK_MARGIN, angleOf(0) + TICK_MARGIN, ARC_WIDTH ); const ZONE_ARC = arcBetween( angleOf(0) - TICK_MARGIN, angleOf(LAST_MARK) + TICK_MARGIN, ZONE_WIDTH ); const TIP = pointOn(0, RADIUS - 6); export interface NeedleMeterProps { "aria-label": string; className?: string; /** The level of the source, in dB, that reads 0 VU. The standard sets none: a studio aligns 0 VU to a level of its own, and -18 dB is a common one for digital audio. @default -18 */ reference?: number; /** A live signal, read each frame outside React: the needle follows its first channel. */ source: Source; } /** * A VU meter: the standard dial, from -20 to +3 VU with its marks spread by * voltage and the part above 0 in red, and a needle with the standard * ballistics, 300 ms to 99% of a step and a 1.3% overshoot. The needle is * turned straight in the DOM each frame, so the dial does not re-render with * the signal. */ export function NeedleMeter({ "aria-label": ariaLabel, className, reference = -18, source, }: NeedleMeterProps) { const needleRef = useRef(null); const readingRef = useRef(null); useEffect(() => { const needle = needleRef.current; if (!needle) { return; } const meter = createVuBallistics(); let frame = 0; let last = performance.now(); let shown = Number.NaN; const tick = (now: number) => { const level = source.getSnapshot().levels[0] ?? FLOOR_DB; const vu = meter.step(level - reference, (now - last) / 1000); last = now; needle.style.transform = `rotate(${angleOf(vu)}deg)`; const rounded = Math.round(vu); if (readingRef.current && rounded !== shown) { shown = rounded; readingRef.current.textContent = `${rounded <= FLOOR_DB ? "-∞" : rounded} VU`; } frame = requestAnimationFrame(tick); }; frame = requestAnimationFrame(tick); return () => cancelAnimationFrame(frame); }, [reference, source]); return (
{`0 VU = ${reference} dB`} -∞ VU
); } ``` **3. Update the import paths to match your project setup.** **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the needle meter from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Usage It takes the same live `source` as [Meter](/docs/components/base/meter#feeding-real-levels), such as the one `use-audio-levels` makes. ```tsx import { NeedleMeter } from "@/components/audio-ui/needle-meter"; ; ``` The standard fixes no level for 0 VU: a studio aligns it to one of its own. `reference` is the level of the source, in dB, that reads 0 VU, and the caption shows it. `-18` is a common one for digital audio. ## The standard The dial and the needle follow the VU meter standard, ANSI C16.5 and IEC 60268-17. - **Marks**: -20, -10, -7, -5, -3, -2, -1, 0, +1, +2 and +3 VU. - **Spacing**: the needle follows the voltage of the signal, not its dB, so 0 VU sits at 71% of the dial and -20 VU at 7%, and the marks crowd toward the top. - **Ballistics**: the needle first reaches 99% of a step in 300 ms and overshoots it by 1.3%, and falls as it rises. - **Rest**: with no signal the needle rests at the left stop, below -20 VU. For a dial of your own, `@audio-ui/core/meter` has the two parts: `vuDeflection` gives the position of a mark, with `levelPosition` from `Number.NEGATIVE_INFINITY` to +3, and `createVuBallistics` the movement of the needle. ## Accessibility The dial is an image with the name you give it. The needle and the reading move too fast to announce, so they are not read out. ## API reference ### NeedleMeter | Prop | Type | Default | Description | | --- | --- | --- | --- | | `aria-label` | `string` | | The accessible name of the meter. | | `source` | `Source` | | A live signal, read each frame outside React: the needle follows its first channel, whose levels are in dB. | | `reference` | `number` | `-18` | The level of the source, in dB, that reads 0 VU. | | `className` | `string` | | Styles the root. | --- # Pad > A grid of drum pads struck by pointer, touch or keyboard, with velocity and choke groups. ```tsx "use client"; import type { Pad as PadPrimitive } from "@audio-ui/react"; import { useCallback, useRef } from "react"; import { Pad, PadItem } from "@/components/audio-ui/pad"; import { useMasterBus } from "@/hooks/use-master-bus"; import { triggerHihat, triggerKick, triggerSnare, } from "@/lib/drum-synthesis"; import { webAudio } from "@/lib/web-audio"; const VOLUME = 0.7; /** How long the open hat rings, in seconds, unless the closed one chokes it. */ const OPEN_HAT_DECAY = 0.6; /** How fast a choked sound fades out, as a time constant in seconds. */ const CHOKE_FADE = 0.01; type Trigger = ( ctx: AudioContext, destination: AudioNode, time: number ) => void; const PADS: { chokeGroup?: string; label: string; trigger: Trigger; value: string; }[] = [ { label: "Kick", trigger: triggerKick, value: "kick" }, { label: "Snare", trigger: triggerSnare, value: "snare" }, { chokeGroup: "hat", label: "Closed hat", trigger: triggerHihat, value: "closed-hat", }, { chokeGroup: "hat", label: "Open hat", trigger: (ctx, destination, time) => triggerHihat(ctx, destination, time, { decay: OPEN_HAT_DECAY }), value: "open-hat", }, ]; /** Four drum pads: strike harder near the top. The closed hat cuts the open one short, as on a drum machine. */ export function PadDemo() { const master = useMasterBus(VOLUME); // The hits each pad still has ringing, so a choke can silence them. const ringing = useRef(new Map()); const strike = useCallback( (value: string, details: PadPrimitive.Root.OnEventDetails) => { const ctx = webAudio.getContext(); const pad = PADS.find((item) => item.value === value); if (!(ctx && master && pad)) { return; } if (ctx.state === "suspended") { ctx.resume(); } // Each hit goes through a gain of its own: how hard the pad was struck. const hit = ctx.createGain(); hit.gain.value = details.velocity; hit.connect(master); pad.trigger(ctx, hit, ctx.currentTime); if (pad.chokeGroup) { ringing.current.set(value, [ ...(ringing.current.get(value) ?? []), hit, ]); } }, [master] ); // Drum hits ring on after the pad is released: only a choke stops them. const choke = useCallback( (value: string, details: PadPrimitive.Root.OffEventDetails) => { const ctx = webAudio.getContext(); if (!ctx || details.reason !== "choke") { return; } for (const hit of ringing.current.get(value) ?? []) { hit.gain.setTargetAtTime(0, ctx.currentTime, CHOKE_FADE); } ringing.current.delete(value); }, [] ); return ( {PADS.map((pad) => ( {pad.label} ))} ); } ``` Triggers sounds, for a drum machine, a sampler or a clip launcher. The registry component wraps the `Pad` primitive from `@audio-ui/react` and lays the pads out in a grid of `columns`. ## Overview - **Events:** `onPadOn(value, eventDetails)` and `onPadOff(value, eventDetails)` report the pad's `value`, ready for an audio engine. `eventDetails.velocity` says how hard it was struck, from 0 to 1, and `eventDetails.cancel()` in `onPadOn` keeps the pad silent. - **Velocity:** a pen or a pressure-sensitive screen strikes as hard as it presses. Other pointers strike harder toward the top of the pad. The keyboard strikes at `0.8`. Each pad exposes its last velocity as `--pad-velocity`, so the flash can follow it. - **Choke groups:** pads sharing a `chokeGroup` stop each other, like a closed hihat cutting an open one. Striking one fires `onPadOff` with `reason: "choke"` for the last pad struck in its group, held or still ringing. - **Pointer:** each pointer holds its own pad, so several play at once on a touch screen. Sliding off a pad does not strike the next one. - **External pads:** `activePads` lights pads from outside, such as the steps of a sequencer, without calling `onPadOn` or `onPadOff`. - **Accessibility:** each pad is a button named by its content, behind one tab stop. The arrow keys move between pads, and Space or Enter holds the focused pad until it is released. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/pad ``` **Manual** **1. Install the following dependencies:** ```bash npm install @audio-ui/react ``` **2. Copy and paste the following code into your project.** ```tsx title="components/audio-ui/pad.tsx" "use client"; import { Pad as PadPrimitive } from "@audio-ui/react"; import type { CSSProperties } from "react"; import { cn } from "@/lib/utils"; type PadProps = Omit & { className?: string; style?: CSSProperties; }; /** * A grid of pads to strike, `columns` to a row. Each pad sounds while held, * by pointer or with Enter or Space, and flashes as hard as it was struck. The * arrow keys move between pads. */ function Pad({ className, columns = 4, style, ...props }: PadProps) { return ( ); } type PadItemProps = Omit & { className?: string; }; /** One pad: give it a `value`, and a label as its content or `aria-label`. */ function PadItem({ className, ...props }: PadItemProps) { return ( ); } export { Pad, PadItem }; ``` **3. Update the import paths to match your project setup.** **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the pad from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Anatomy Import the primitive and assemble its parts. ```tsx import { Pad } from "@audio-ui/react"; Kick ``` ## Usage ```tsx import { Pad, PadItem } from "@/components/audio-ui/pad"; ``` **Pad events:** ```tsx sampler.trigger(value, velocity)} > Kick Snare ``` **Choke groups (a closed hat cuts the open one):** ```tsx { if (reason === "choke") { sampler.stop(value); } }} onPadOn={(value, { velocity }) => sampler.trigger(value, velocity)} > Closed hat Open hat ``` ## Interaction ### Pointer **Behavior** | Gesture | Effect | | --- | --- | | Press a pad | Fires `onPadOn` with a velocity; the pad stays active while held. | | Release | Fires `onPadOff`. | | Multiple pointers | Each pointer (finger) holds its own pad, so several play at once on touch devices. | ### Keyboard The pads share one tab stop. On the focused pad: **Keys** | Key | Effect | | --- | --- | | `ArrowLeft` / `ArrowRight` | Move focus to the previous / next pad in reading order | | `ArrowUp` / `ArrowDown` | Move focus a row up / down | | `Space` / `Enter` | Hold the focused pad: `onPadOn` on press, `onPadOff` on release | | `Home` / `End` | Move focus to the first / last pad | ## API reference ### Root A grid of pads to strike: each one sounds while held, by pointer or from the keyboard, and each pointer holds its own pad, so several can be played at once on a touch screen. A strike is harder where a pen or screen presses harder, or else toward the top of the pad. The pads are one tab stop: the left and right arrows walk them in reading order, the up and down arrows by a row of `columns`. Renders a `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `activePads` | `readonly string[]` | | Pads lit from elsewhere, such as a sequencer or a MIDI input, on top of the ones held here. | | `columns` | `number` | `4` | How many pads a row holds: what the up and down arrows move by. Lay the grid out to match. | | `disabled` | `boolean` | | | | `onPadOff` | `(value: string, eventDetails: OffEventDetails) => void` | | Fires when a pad is released, loses focus while held, or is choked by another pad of its group (`reason: "choke"`). | | `onPadOn` | `(value: string, eventDetails: OnEventDetails) => void` | | Fires when a pad is struck, with `eventDetails.velocity` from 0 to 1. `eventDetails.cancel()` keeps it silent. | **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | ### Item One pad. It sounds while held: by pointer, or with Enter or Space while focused. Its accessible name comes from its content, or `aria-label`. How hard it was last struck is the `--pad-velocity` CSS variable, from 0 to 1. Renders a ` ``` Everything `useMidiInput` gives is in [Input](/docs/engine/input). ## Interaction ### Pointer **Behavior** | Gesture | Effect | | --- | --- | | Press a key | Fires `onNoteOn`; the key stays pressed while held. | | Release | Fires `onNoteOff`. | | Drag across keys | Glissando: the previous key releases (`onNoteOff`) and the next one sounds (`onNoteOn`) as the pointer crosses it. | | Multiple pointers | Each pointer (finger) holds its own key, so chords work on touch devices. | ### Keyboard The keys share one tab stop. On the focused key: **Keys** | Key | Effect | | --- | --- | | `ArrowLeft` / `ArrowRight` (or `ArrowDown` / `ArrowUp`) | Move focus to the next lower / higher key | | `Shift` + arrow, `PageDown` / `PageUp` | Move focus an octave down / up | | `Space` / `Enter` | Hold the focused key: `onNoteOn` on press, `onNoteOff` on release | | `Home` / `End` | Move focus to the lowest / highest key | ## API reference ### Root A keyboard to play: every key sounds while pressed, by pointer or from the keyboard. Dragging across the keys glides from one to the next, and each pointer holds its own key, so chords can be played on a touch screen. It is laid out like a piano, or with `layout="even"` as one equal share per key, the way a piano roll's rows are; `orientation="vertical"` puts the low end at the bottom. The keys are one tab stop, walked with the arrow keys. Renders a `
` element. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `activeNotes` | `readonly number[]` | | Pitches lit from elsewhere, such as a MIDI input or a sequencer, on top of the keys pressed here. | | `disabled` | `boolean` | | | | `layout` | `Layout` | `"keyboard"` | How the keys share the length: like a piano, or one equal share each. | | `maxPitch` | `number` | `72` | Highest MIDI pitch, inclusive. | | `minPitch` | `number` | `48` | Lowest MIDI pitch, inclusive: 60 is middle C. | | `onNoteOff` | `(pitch: number, eventDetails: NoteOffEventDetails) => void` | | Fires when a key is released, the pointer glides off it, or it loses focus while held. | | `onNoteOn` | `(pitch: number, eventDetails: NoteOnEventDetails) => void` | | Fires when a key is pressed or glided onto. `eventDetails.cancel()` keeps it silent. | | `orientation` | `"horizontal" \| "vertical"` | `"horizontal"` | | | `pitches` | `readonly number[]` | | Only these pitches get keys, instead of `minPitch`…`maxPitch`. | **Data attributes** | Attribute | Description | | --- | --- | | `data-disabled` | Present when disabled. | ### Keys Renders `children` once per key, lowest first: the place to put a `Piano.Key` for each pitch. Renders no element of its own. | Prop | Type | Default | Description | | --- | --- | --- | --- | | `children` | `(pitch: number) => React.ReactNode` | | | ### Key One key, placed along the keyboard for its pitch. It sounds while pressed: by pointer through the keyboard, or with Enter or Space while focused. Its accessible name defaults to the pitch, such as "C4". Renders a ` ; ``` Call `start` from a click: the browser asks for permission then, and a suspended audio context resumes. The microphone is released on `stop` and when the component unmounts. The signal is raw: echo cancellation, noise suppression and automatic gain are what a call needs, and they flatten the very level a tuner reads. The analyser is never connected to the speakers, so nothing plays back. ## Pitch of any signal `usePitch` takes any `AnalyserNode`, not only the microphone's: tap a synth, a track or the master bus and the tuner shows what plays. ```tsx const analyser = ctx.createAnalyser(); analyser.fftSize = 4096; // two periods of the lowest pitch: 4096 at 48 kHz reaches about 40 Hz synth.connect(analyser); const pitch = usePitch(analyser, { minHz: 60, maxHz: 1200, reference: 432 }); ``` The detector is the YIN algorithm, in `@audio-ui/core/pitch`: `detectPitch(samples, sampleRate)` for the frequency of an array of samples, `nearestNote(frequency)` for the note and its offset in cents, and `noteToFrequency` for the way back. They are pure functions with no React and no Web Audio, so you can use them off the audio thread, in a test or in any framework. ## Accessibility The tuner is a `meter` of cents, from -50 to +50, and its text value reads the note and how far off it is: "A 4, 12 cents flat", "A 4, in tune", "No sound". The display itself is hidden from assistive technology, so a screen reader does not read a new figure twenty times a second. ## API reference ### Tuner | Prop | Type | Default | Description | | --- | --- | --- | --- | | `source` | `Source` | | The live reading, such as `usePitch` returns: the note, its octave, the offset in cents and the frequency, or `null` while nothing clear is playing. | | `tolerance` | `number` | `5` | How far from the note still counts as in tune, in cents. The display turns to the primary color within it. | | `className` | `string` | | Styles the root. | ### useMicrophone Its reference is in [Input](/docs/engine/input#the-microphone). ### usePitch | Prop | Type | Default | Description | | --- | --- | --- | --- | | `analyser` | `AnalyserNode \| null` | | The signal to read, with an `fftSize` of at least two periods of `minHz`. | | `reference` | `number` | `440` | The frequency of A4 in hertz. | | `minHz` | `number` | `40` | The lowest pitch looked for. | | `maxHz` | `number` | `2000` | The highest pitch looked for. | | `minLevel` | `number` | `0.01` | How quiet the signal may be, as an RMS level from 0 to 1, before nothing is detected. | | `threshold` | `number` | `0.15` | How aperiodic a period may be and still count. Lower is stricter. | | `median` | `number` | `5` | How many recent detections the reading is the median of: it drops the octave jumps a plucked string starts with. | | `holdMs` | `number` | `600` | How long the last note stays after the sound stops, so a string's decay does not flicker. | --- # Value Display > An audio value as it reads, in steady monospace figures, for tempo, level, frequency, pan, percent, semitones and time. An audio value as a DAW shows it, in monospace figures that do not jump as they change: `120.00 BPM`, `-6.0 dB`, `1.2 kHz`, `L 30`, `50 %`, `+3 st`, `1:02.345`. ## Installation **CLI** ```bash npx shadcn@latest add @audio-ui/value-display ``` **Manual** **1. Install the following dependencies:** ```bash npm install @audio-ui/core class-variance-authority ``` **2. Copy and paste the following code into your project.** ```tsx title="components/audio-ui/value-display.tsx" import { formatDb, formatHz } from "@audio-ui/core/analysis"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; /** What a value is, which says how it reads. */ export type ValueKind = | "bpm" | "db" | "hz" | "pan" | "percent" | "semitones" | "time"; const SIGNED = new Intl.NumberFormat("en-US", { maximumFractionDigits: 0, signDisplay: "exceptZero", }); /** Minutes, seconds and milliseconds: 1:02.345. */ function formatTime(seconds: number) { const whole = Math.max(0, seconds); const minutes = Math.floor(whole / 60); const rest = whole - minutes * 60; return `${minutes}:${rest.toFixed(3).padStart(6, "0")}`; } /** A pan from -1 to 1: C in the middle, L or R and how far, in percent. */ function formatPan(pan: number) { const amount = Math.round(Math.abs(pan) * 100); if (amount === 0) { return "C"; } return `${pan < 0 ? "L" : "R"} ${amount}`; } /** How a value of each kind reads: as a DAW shows it. */ export function formatValue(value: number, kind: ValueKind): string { switch (kind) { case "bpm": return `${value.toFixed(2)} BPM`; case "db": return formatDb(value); case "hz": return formatHz(value); case "pan": return formatPan(value); case "percent": return `${Math.round(value * 100)} %`; case "semitones": return `${SIGNED.format(value)} st`; default: return formatTime(value); } } const valueDisplayVariants = cva("font-mono tabular-nums tracking-tight inline-block", { defaultVariants: { size: "default" }, variants: { /** "lg" for the main value of a panel. */ size: { default: "text-sm", lg: "font-medium text-2xl", sm: "text-xs", }, }, }); export interface ValueDisplayProps extends VariantProps { className?: string; /** How it reads: a tempo, a level, a frequency, a pan, a share, a pitch, a time. */ kind: ValueKind; /** Names it for assistive technology, which reads it with its value: "Cutoff". */ label?: string; value: number; } /** * A value as it reads, in monospace figures that do not jump as they change: * 120.00 BPM, -6.0 dB, 1.2 kHz, L 30, 50 %, +3 st, 1:02.345. `formatValue` * gives the same text, for a title or an announcement. */ export function ValueDisplay({ className, kind, label, size, value, }: ValueDisplayProps) { const text = formatValue(value, kind); return ( {text} ); } ``` **3. Update the import paths to match your project setup.** **Agent** Give your agent the skill, and it picks the component, installs it and wires it to your audio: ```bash npx skills add ouestlabs/audio-ui ``` Then ask it: ```text Add the value display from audio/ui to my project and wire it to my audio code. ``` To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents). ## Usage ```tsx import { formatValue, ValueDisplay } from "@/components/audio-ui/value-display"; // The same text, for a title or an announcement. formatValue(gain, "db"); ``` | `kind` | Value | Reads | | --- | --- | --- | | `bpm` | beats per minute | `120.00 BPM` | | `db` | decibels, `-Infinity` for silence | `-6.0 dB`, `-∞ dB` | | `hz` | hertz | `440 Hz`, `1.2 kHz` | | `pan` | -1 to 1 | `L 30`, `C`, `R 100` | | `percent` | 0 to 1 | `50 %` | | `semitones` | semitones | `+3 st` | | `time` | seconds | `1:02.345` | ## API reference | Prop | Type | Default | Description | | --- | --- | --- | --- | | `value` | `number` | | The value. | | `kind` | `ValueKind` | | How it reads: a tempo, a level, a frequency, a pan, a share, a pitch, a time. | | `label` | `string` | | Names it for assistive technology, which reads it with its value: "Cutoff". | | `size` | `"sm" \| "default" \| "lg"` | `"default"` | "lg" for the main value of a panel. | --- # Waveform > Draws audio: a seekable waveform with regions and markers, a live waveform that scrolls with the signal, and a bar visualizer. ```tsx "use client"; 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([48, 96]); return (
Verse Chorus

Loop {formatTime(loop[0])} – {formatTime(loop[1])}

); } ``` 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 wrap the `Waveform` primitive from `@audio-ui/react`, which works with any audio: decoded PCM samples, a microphone or a stream from your server. ## 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 `