# Mixer

> The mixer of an arrangement, controlled: a channel for each track and return with pan, sends, fader, meter, peak, solo and mute, then the main track, every meter reading the real signal of its channel.

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

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

const REVERB = "return-1";

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

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

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

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

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

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

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

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

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

A channel for each track and each return track, then the main track. Each channel has its pan, its sends, its fader, its meter and its loudest peak, and Solo, Mute and, for a track that records, an Arm light. It is built from the [Knob](/docs/components/base/knob), [Fader](/docs/components/base/fader) and [Meter](/docs/components/base/meter), and it is the mixer a workstation shows under its tracks: the state is an [arrangement](/docs/components/base/arrangement), and every change is one of its commands.

## Installation

**CLI**

```bash
npx shadcn@latest add @audio-ui/block-mixer
```

**Manual**

**1. Install the following dependencies:**

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

**2. Add the components and hooks it is made of:**

```bash
npx shadcn@latest add @audio-ui/mixer-view @audio-ui/arrangement @audio-ui/use-arrangement @audio-ui/arrangement-engine @audio-ui/track-automation @audio-ui/use-play-switch @audio-ui/demo-sound @audio-ui/device-library @audio-ui/web-audio @audio-ui/clip-player
```

**3. Copy and paste the following code into your project.**

<ItemFiles name="block-mixer" />

**4. Update the import paths to match your project setup.**

**Agent**

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

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

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

## Usage

`mixer-view` (`npx shadcn@latest add @audio-ui/mixer-view`) is the view on its own. It is controlled: the arrangement comes in through `useArrangement`, and every change goes out as a command or through `onMix`.

```tsx
import { MixerView } from "@/components/audio-ui/mixer-view";

<MixerView
  arrangement={arrangement} // useArrangement
  engine={engine} // useArrangementEngine: the position and each channel's meter
  onMix={automation.changeMix} // a fader, a pan or a switch of a channel
  onSelectTrack={setSelected}
  overridden={automation.overridden} // what was moved by hand, by track
  selectedTrack={selected}
/>;
```

`armed` and `onArm` add an Arm light to the channels of tracks that record. Leave them out and no channel has one.

## A channel

- **Pan and sends** are knobs, dragged up and down; a send is a small knob for each return track. A channel with no output, such as a MIDI track with no instrument, has none of them, nor a fader or a peak.
- **The fader** runs from silence to +6 dB, 0 dB by default, and a double-click sets it back to 0. It is the same fader as the track's in the arrangement: one moves the other.
- **The meter** shows the channel's peak and its level, after its fader and its switches; the main track has a scale beside its own.
- **The peak** is the loudest sample the channel has played, in dB, in a pill over its pan. It turns red past 0 dBFS, and a click clears it.
- **The loudness** of the mix, in the main track's channel under its fader: its integrated loudness in LUFS since it was last cleared, what streaming services and broadcasters hold a file to (-14 LUFS for streaming). A click clears it.
- **Solo, Mute and Arm** are the same state as the track's header in the arrangement, in one group.

The main track stays in sight at the right, apart from the channels by a line, while the channels scroll; the return tracks follow the tracks' channels and scroll with them. A channel moves by its name: dragged, or picked up with Space or Enter, moved with the arrows, Home and End, dropped with Space or Enter and put back with Escape. Each step is announced, a group moves with its tracks, and the arrangement's rows follow once it lands. A track in a group names the group it plays into.

## Meters

The meters read the engine's channels: `engine.meter(id)` gives the `AnalyserNode`s of a track, and a meter takes a live `source`, so a channel costs no React render per frame. `useAudioLevels` makes one from the analysers:

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

const levels = useAudioLevels(analysers); // memoize the array: a new one restarts sampling

<Meter aria-label="Drums level" peakMarks="hidden" source={levels} />;
```

The level is the RMS of the time-domain samples in dB. It rises at once and falls back at 30 dB a second, so a drum hit reads as a hit and does not flicker. Nothing is published while the signal is silent. The analysers are never connected to `ctx.destination`, so reading a level plays nothing.

## Over an engine of your own

The view asks three things of the engine: `position`, a live source of seconds, `meter(id)`, the analysers of a track by its id, or `null` when there are none yet, and `tap(id)`, the node the main track's sound passes through after its volume, which its loudness is read from (`useLoudness`), or `null`. Any engine that gives those, an AudioWorklet or WASM one, drives the view; the commands of the arrangement tell it what to play.

## Accessibility

Every control is a native input behind its own role: the pan is a slider named "Drums pan" and the volume "Drums volume", and mute and solo are toggle buttons, "Mute Drums" and "Solo Drums". A channel is a group with the track's name, so a screen reader reads "Drums, group" then each control, and tabbing goes through its pan, sends, volume, then its switches, then the next track. The faders and knobs take the arrow keys, Home and End.
