# Blocks (/docs/blocks)
Blocks wire audiocn components to the Web Audio hooks. Each one installs everything it needs in one command, and after that the code is yours: it has few props and is meant to be edited.
| Block | What it is |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------ |
| [System Audio Mixer](/docs/blocks/system-audio-mixer) | Microphone, system audio, music, sound pads and a master, running on Web Audio |
| [Microphone Setup](/docs/blocks/mic-setup) | Device select, live preview, meter, gain, mute and a level check |
| [System Audio Settings](/docs/blocks/system-audio-settings) | On/off capture, level, meter and what the browser will capture |
| [Quick Audio Popover](/docs/blocks/quick-audio-popover) | Microphone and system audio controls behind one toolbar button |
| [Soundboard](/docs/blocks/soundboard) | Sound pads with hotkeys, modes, volume and drag-and-drop |
| [Music Player](/docs/blocks/music-player) | Playlist, waveform seek bar, shuffle, repeat and ducking |
> **Demo audio**
>
> The previews play music and sound effects synthesised in your browser, so no
> audio files ship with the site. In your app, pass your own tracks and sounds.
# Microphone Setup (/docs/blocks/mic-setup)
```tsx title="components/examples/mic-setup-demo.tsx"
"use client";
import { MicSetup } from "@/components/blocks/mic-setup/mic-setup";
const MicSetupDemo = () => ;
export default MicSetupDemo;
```
## Installation
```bash
npx shadcn@latest add @audiocn/mic-setup
```
## What it does
* Lists microphones and asks for access when needed.
* Shows a scrolling waveform and a meter with peak hold, a scale and a clip light.
* Applies gain (−24 to +24 dB) and mute to what the meter shows.
* "Check level" listens for three seconds and says whether the level is good, too quiet, too loud or silent.
The microphone opens when the user clicks "Turn on microphone", or on mount with `autoStart`.
## Props
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `deviceId / onDeviceChange` | `string \| null` | — | Optional control of the selected device. |
| `gainDb / onGainChange` | `number` | `0` | — |
| `muted / onMutedChange` | `boolean` | `false` | — |
| `autoStart` | `boolean` | `false` | Open the microphone on mount. |
## Files
```tsx title="components/blocks/mic-setup/mic-setup.tsx"
"use client";
import {
CheckCircleIcon,
MicrophoneIcon,
WarningCircleIcon,
} from "@phosphor-icons/react";
import { useEffect, useId, useRef, useState } from "react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
AudioDeviceSelect,
AudioDeviceSelectContent,
AudioDeviceSelectPreview,
AudioDeviceSelectTrigger,
AudioDeviceSelectValue,
} from "@/components/ui/audio-device-select";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { DbReadout } from "@/components/ui/db-readout";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import {
LevelMeter,
LevelMeterBar,
LevelMeterChannel,
LevelMeterChannels,
LevelMeterClip,
LevelMeterHold,
LevelMeterScale,
LevelMeterTrack,
} from "@/components/ui/level-meter";
import { LiveWaveform } from "@/components/ui/live-waveform";
import {
ParameterSlider,
ParameterSliderControl,
ParameterSliderHeader,
ParameterSliderInput,
ParameterSliderLabel,
ParameterSliderReset,
} from "@/components/ui/parameter-slider";
import { Switch } from "@/components/ui/switch";
import { useAudioAnalyser } from "@/hooks/use-audio-analyser";
import { useAudioDevices } from "@/hooks/use-audio-devices";
import { useGainNode } from "@/hooks/use-gain-node";
import { useMicrophone } from "@/hooks/use-microphone";
import { dbToGain } from "@/lib/audio/decibels";
import type { FrameSource, MeterFrame } from "@/lib/audio/types";
const CHECK_DURATION_MS = 3000;
type CheckResult = "good" | "quiet" | "loud" | "silent";
const RESULTS: Record<
CheckResult,
{ title: string; description: string; ok: boolean }
> = {
good: {
description: "Your level sits in the right range.",
ok: true,
title: "Sounds good",
},
loud: {
description: "Your voice clipped. Lower the gain.",
ok: false,
title: "Too loud",
},
quiet: {
description: "Raise the gain or move closer.",
ok: false,
title: "Too quiet",
},
silent: {
description: "Check the device and that it is not muted.",
ok: false,
title: "No signal",
},
};
const judge = (peakDb: number): CheckResult => {
if (peakDb < -55) {
return "silent";
}
if (peakDb >= -1) {
return "loud";
}
if (peakDb < -30) {
return "quiet";
}
return "good";
};
/** Runs the microphone through a gain stage and analyses the result. */
const useMicInput = (
stream: MediaStream | null,
gainDb: number,
muted: boolean
) => {
// Not routed to the speakers: the analyser taps it, and nothing else.
const gainNode = useGainNode({
destination: null,
gain: muted ? 0 : dbToGain(gainDb),
input: stream,
});
return useAudioAnalyser(stream ? gainNode : null, { historySize: 120 });
};
/** Listens for a few seconds, then judges the loudest peak. */
const useLevelCheck = (meter: FrameSource) => {
const [checking, setChecking] = useState(false);
const [result, setResult] = useState(null);
const peakRef = useRef(Number.NEGATIVE_INFINITY);
useEffect(() => {
if (!checking) {
return;
}
peakRef.current = Number.NEGATIVE_INFINITY;
const unsubscribe = meter.subscribe((frame) => {
for (const level of frame.channels) {
peakRef.current = Math.max(peakRef.current, level.peakDb);
}
});
const timer = setTimeout(() => {
setChecking(false);
setResult(judge(peakRef.current));
}, CHECK_DURATION_MS);
return () => {
unsubscribe();
clearTimeout(timer);
};
}, [checking, meter]);
const start = () => {
setResult(null);
setChecking(true);
};
return { checking, result, start };
};
export interface MicSetupProps {
deviceId?: string | null;
onDeviceChange?: (deviceId: string | null) => void;
gainDb?: number;
onGainChange?: (gainDb: number) => void;
muted?: boolean;
onMutedChange?: (muted: boolean) => void;
/** Open the microphone on mount instead of waiting for a click. Default false. */
autoStart?: boolean;
className?: string;
}
export const MicSetup = ({
deviceId: deviceIdProp,
onDeviceChange,
gainDb: gainDbProp,
onGainChange,
muted: mutedProp,
onMutedChange,
autoStart = false,
className,
}: MicSetupProps) => {
const muteId = useId();
const [started, setStarted] = useState(autoStart);
const [deviceIdState, setDeviceIdState] = useState(null);
const [gainState, setGainState] = useState(0);
const [mutedState, setMutedState] = useState(false);
const deviceId = deviceIdProp === undefined ? deviceIdState : deviceIdProp;
const gainDb = gainDbProp ?? gainState;
const muted = mutedProp ?? mutedState;
const devices = useAudioDevices();
const microphone = useMicrophone({ deviceId, enabled: started });
const analyser = useMicInput(microphone.stream, gainDb, muted);
const { checking, result, start: startCheck } = useLevelCheck(analyser.meter);
const setDeviceId = (next: string | null) => {
setDeviceIdState(next);
onDeviceChange?.(next);
};
const setGain = (next: number) => {
setGainState(next);
onGainChange?.(next);
};
const setMuted = (next: boolean) => {
setMutedState(next);
onMutedChange?.(next);
};
const active = microphone.status === "active";
const verdict = result ? RESULTS[result] : null;
return (
Microphone
Pick a microphone and check your level.
Device devices.requestPermission()}
onValueChange={setDeviceId}
permission={
devices.permission === "unsupported"
? "denied"
: devices.permission
}
value={deviceId}
>
{active ? null : (
)}
Level
GainMute microphone
{verdict ? (
{verdict.ok ? : }
{verdict.title}{verdict.description}
) : null}
{microphone.status === "denied" ? (
Microphone blocked
Allow microphone access in your browser's site settings.
) : null}
);
};
```
# Music Player (/docs/blocks/music-player)
```tsx title="components/examples/music-player-demo.tsx"
"use client";
import { MusicPlayer } from "@/components/blocks/music-player/music-player";
import { useDemoTracks } from "@/lib/docs/use-demo-audio";
const MusicPlayerDemo = () => {
const tracks = useDemoTracks();
if (tracks.length === 0) {
return
Preparing tracks…
;
}
return ;
};
export default MusicPlayerDemo;
```
## Installation
```bash
npx shadcn@latest add @audiocn/music-player
```
## What it does
* A player with a [waveform](/docs/components/waveform) seek bar that shows what has played, hover time, and elapsed and remaining time.
* A [track list](/docs/components/track-list): select a track to play it; the list advances on its own.
* Shuffle, repeat all and repeat one.
* With a `duckingSource`, the music drops while the source is active, with an on/off switch and an amount. It comes back on its own when the source goes quiet or stops.
## Ducking under the microphone
```tsx title="components/examples/music-player-ducking.tsx"
"use client";
import { MusicPlayer } from "@/components/blocks/music-player/music-player";
import { Button } from "@/components/ui/button";
import { useAudioAnalyser } from "@/hooks/use-audio-analyser";
import { useMicrophone } from "@/hooks/use-microphone";
import { useDemoTracks } from "@/lib/docs/use-demo-audio";
const MusicPlayerDucking = () => {
const tracks = useDemoTracks();
const microphone = useMicrophone();
const analyser = useAudioAnalyser(microphone.stream);
const listening = microphone.status === "active";
return (
{tracks.length > 0 ? (
) : null}
);
};
export default MusicPlayerDucking;
```
## Props
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `tracks / defaultTracks` | `{ id, title, artist?, src, artwork?, duration? }[]` | `[]` | — |
| `onTrackChange` | `(track) => void` | — | — |
| `duckingSource` | `FrameSource \| null` | — | The signal that ducks the music, usually the microphone. |
| `output` | `AudioNode \| null` | `speakers` | Route the music into a mixer. |
## Files
```tsx title="components/blocks/music-player/music-player.tsx"
"use client";
import {
MusicNotesIcon,
PauseIcon,
PlayIcon,
RepeatIcon,
RepeatOnceIcon,
ShuffleIcon,
SkipBackIcon,
SkipForwardIcon,
SpeakerHighIcon,
SpeakerXIcon,
} from "@phosphor-icons/react";
import { useEffect, useId, useMemo, useState } from "react";
import {
AudioPlayer,
AudioPlayerArtwork,
AudioPlayerControls,
AudioPlayerDescription,
AudioPlayerNext,
AudioPlayerPlay,
AudioPlayerPrevious,
AudioPlayerTime,
AudioPlayerTitle,
AudioPlayerVolume,
} from "@/components/ui/audio-player";
import { Card, CardContent } from "@/components/ui/card";
import {
Empty,
EmptyDescription,
EmptyHeader,
EmptyMedia,
EmptyTitle,
} from "@/components/ui/empty";
import { Label } from "@/components/ui/label";
import {
ParameterSlider,
ParameterSliderControl,
ParameterSliderHeader,
ParameterSliderLabel,
ParameterSliderValue,
} from "@/components/ui/parameter-slider";
import { Switch } from "@/components/ui/switch";
import { Toggle } from "@/components/ui/toggle";
import {
TrackList,
TrackListItem,
TrackListItemContent,
TrackListItemDescription,
TrackListItemDuration,
TrackListItemIndex,
TrackListItemTitle,
} from "@/components/ui/track-list";
import {
VolumeControlMute,
VolumeControlSlider,
} from "@/components/ui/volume-control";
import {
Waveform,
WaveformCanvas,
WaveformCursor,
WaveformHover,
} from "@/components/ui/waveform";
import { getMediaElementSource } from "@/hooks/use-audio-analyser";
import { useAudioContext } from "@/hooks/use-audio-context";
import { useAudioPlayer } from "@/hooks/use-audio-player";
import { useFrameSource } from "@/hooks/use-frame-source";
import { useWaveformData } from "@/hooks/use-waveform-data";
import { dbToGain } from "@/lib/audio/decibels";
import { formatTime } from "@/lib/audio/time";
import type { FrameSource, MeterFrame } from "@/lib/audio/types";
export interface MusicTrack {
id: string;
title: string;
artist?: string;
src: string;
artwork?: string;
/** Seconds, shown before the file loads. */
duration?: number;
}
export interface MusicPlayerProps {
tracks?: MusicTrack[];
defaultTracks?: MusicTrack[];
onTrackChange?: (track: MusicTrack) => void;
/** A level source, usually the microphone, that ducks the music. */
duckingSource?: FrameSource | null;
/** Route the music into a mixer instead of the speakers. */
output?: AudioNode | null;
className?: string;
}
type Repeat = "off" | "all" | "one";
const NO_TRACKS: MusicTrack[] = [];
const DUCK_THRESHOLD_DB = -35;
const DUCK_ATTACK = 0.02;
const DUCK_RELEASE = 0.15;
/** How long a duck holds after the last loud frame before it lets go. */
const DUCK_HOLD = 0.2;
const nextRepeat: Record = {
all: "one",
off: "all",
one: "off",
};
export const MusicPlayer = ({
tracks: tracksProp,
defaultTracks = NO_TRACKS,
onTrackChange,
duckingSource,
output,
className,
}: MusicPlayerProps) => {
const tracks = tracksProp ?? defaultTracks;
const duckingId = useId();
const [index, setIndex] = useState(0);
const [shuffle, setShuffle] = useState(false);
const [repeat, setRepeat] = useState("all");
const [ducking, setDucking] = useState(true);
// Once the listener has played or picked a track, later tracks play on
// their own, including after repeat-all wraps back to the first.
const [autoAdvance, setAutoAdvance] = useState(false);
const [duckAmountDb, setDuckAmountDb] = useState(-12);
const track = tracks[index];
const go = (direction: number) => {
if (tracks.length === 0) {
return;
}
let next = (index + direction + tracks.length) % tracks.length;
if (shuffle && tracks.length > 1) {
next =
(index + 1 + Math.floor(Math.random() * (tracks.length - 1))) %
tracks.length;
}
setIndex(next);
setAutoAdvance(true);
const nextTrack = tracks[next];
if (nextTrack) {
onTrackChange?.(nextTrack);
}
};
const player = useAudioPlayer({
autoPlay: autoAdvance,
loop: repeat === "one",
onEnded: () => {
if (repeat === "all" || index < tracks.length - 1) {
go(1);
}
},
src: track?.src,
});
const waveform = useWaveformData(track?.src ?? null, { samples: 400 });
const { context } = useAudioContext();
const duckGain = useMemo(() => context?.createGain() ?? null, [context]);
const routed = output !== undefined || duckingSource !== undefined;
useEffect(() => {
if (!(context && duckGain && player.element && routed)) {
return;
}
const source = getMediaElementSource(context, player.element);
try {
source.disconnect(context.destination);
} catch {
// Not connected to the speakers.
}
source.connect(duckGain);
const target = output === undefined ? context.destination : output;
if (target) {
duckGain.connect(target);
}
return () => {
source.disconnect(duckGain);
if (target) {
duckGain.disconnect(target);
}
source.connect(context.destination);
};
}, [context, duckGain, output, player.element, routed]);
useFrameSource(
duckingSource,
(frame) => {
if (!(duckGain && context)) {
return;
}
let loudest = Number.NEGATIVE_INFINITY;
for (const level of frame.channels) {
loudest = Math.max(loudest, level.peakDb);
}
if (!(ducking && loudest >= DUCK_THRESHOLD_DB)) {
return;
}
// Each loud frame ducks and schedules its own release, so the music
// comes back when the voice goes quiet or its frames stop arriving
// (the mic is turned off, ducking is switched off).
const now = context.currentTime;
const { gain } = duckGain;
gain.cancelScheduledValues(now);
gain.setTargetAtTime(dbToGain(duckAmountDb), now, DUCK_ATTACK);
gain.setTargetAtTime(1, now + DUCK_HOLD, DUCK_RELEASE);
},
{ enabled: routed && Boolean(duckGain) }
);
if (tracks.length === 0) {
return (
No musicAdd tracks to start playing.
);
}
return (
);
};
```
# System Audio Mixer (/docs/blocks/system-audio-mixer)
```tsx title="components/examples/system-audio-mixer-demo.tsx"
"use client";
import { SystemAudioMixer } from "@/components/blocks/system-audio-mixer/system-audio-mixer";
import { useDemoSounds, useDemoTracks } from "@/lib/docs/use-demo-audio";
const SystemAudioMixerDemo = () => {
const tracks = useDemoTracks();
const sounds = useDemoSounds();
return (
);
};
export default SystemAudioMixerDemo;
```
## Installation
```bash
npx shadcn@latest add @audiocn/system-audio-mixer
```
## What it does
* **Microphone**: choose a device, start and stop it, and see when it is live, muted or blocked.
* **System audio**: capture a screen or tab with its audio through the browser's picker, with notices when nothing was shared or the browser cannot capture.
* **Music**: play and skip tracks. Music ducks by 12 dB while the microphone is active.
* **Sounds**: a popover of sound pads with hotkeys.
* **Every channel** has a stereo meter, a fader, mute, solo and a monitor send to the speakers. Microphone monitoring is off by default to avoid feedback.
* **Master**: a limited stereo mix with a clip counter and a master fader. The mix is available as a `MediaStream` through `onOutputChange`, ready for `MediaRecorder` or WebRTC.
* **Layouts**: switch between rows and console strips.
## Console layout
```tsx title="components/examples/system-audio-mixer-console.tsx"
"use client";
import { SystemAudioMixer } from "@/components/blocks/system-audio-mixer/system-audio-mixer";
import { useDemoSounds, useDemoTracks } from "@/lib/docs/use-demo-audio";
const SystemAudioMixerConsole = () => {
const tracks = useDemoTracks();
const sounds = useDemoSounds();
return (
);
};
export default SystemAudioMixerConsole;
```
## Usage
```tsx
import { SystemAudioMixer } from "@/components/blocks/system-audio-mixer/system-audio-mixer";
recorder.setStream(stream)}
persistKey="studio-mixer"
sounds={[{ id: "ding", label: "Ding", src: "/sounds/ding.mp3", hotkey: "1" }]}
tracks={[{ id: "intro", title: "Intro", src: "/music/intro.mp3" }]}
/>;
```
## Props
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `defaultOrientation` | `"horizontal" \| "vertical"` | `"horizontal"` | Rows or console strips. |
| `sources` | `("microphone" \| "system" \| "music" \| "sounds")[]` | `all four` | Which strips to show. |
| `persistKey` | `string` | — | Save mixer settings to localStorage. |
| `onOutputChange` | `(stream: MediaStream \| null) => void` | — | The mixed output. |
| `tracks` | `{ id, title, artist?, src }[]` | `[]` | Tracks for the music channel. |
| `sounds` | `{ id, label, src, hotkey?, accent? }[]` | `[]` | Sounds for the sounds channel. |
## Files
```tsx title="components/blocks/system-audio-mixer/system-audio-mixer.tsx"
"use client";
import {
ArrowCounterClockwiseIcon,
DesktopIcon,
GearSixIcon,
MicrophoneIcon,
MusicNotesIcon,
PauseIcon,
PlayIcon,
SkipForwardIcon,
SquaresFourIcon,
WaveformIcon,
} from "@phosphor-icons/react";
import { useEffect, useEffectEvent, useState } from "react";
import { MixerMasterStrip } from "@/components/blocks/system-audio-mixer/mixer-master-strip";
import { MixerSourceStrip } from "@/components/blocks/system-audio-mixer/mixer-source-strip";
import { AudioDeviceSelect } from "@/components/ui/audio-device-select";
import { Button } from "@/components/ui/button";
import { ChannelStripNotice } from "@/components/ui/channel-strip";
import type { ChannelStripStatusProps } from "@/components/ui/channel-strip";
import {
Mixer,
MixerActions,
MixerChannels,
MixerEmpty,
MixerHeader,
MixerMaster,
MixerSeparator,
MixerTitle,
} from "@/components/ui/mixer";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import {
SoundPad,
SoundPadGrid,
SoundPadLabel,
SoundPadProgress,
SoundPadShortcut,
} from "@/components/ui/sound-pad";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useAudioDevices } from "@/hooks/use-audio-devices";
import { useAudioPlayer } from "@/hooks/use-audio-player";
import type { AudioPlayerController } from "@/hooks/use-audio-player";
import { useGainNode } from "@/hooks/use-gain-node";
import { useMicrophone } from "@/hooks/use-microphone";
import type { UseMicrophoneResult } from "@/hooks/use-microphone";
import { useMixer } from "@/hooks/use-mixer";
import type { Mixer as MixerController } from "@/hooks/use-mixer";
import { useSound } from "@/hooks/use-sound";
import { useSystemAudio } from "@/hooks/use-system-audio";
import type { UseSystemAudioResult } from "@/hooks/use-system-audio";
import { useWebAudioMixer } from "@/hooks/use-web-audio-mixer";
import type { FrameSource, MeterFrame, Orientation } from "@/lib/audio/types";
import { cn } from "@/lib/utils";
export type MixerSourceId = "microphone" | "system" | "music" | "sounds";
export interface MixerTrack {
id: string;
title: string;
artist?: string;
src: string;
}
export interface MixerSound {
id: string;
label: string;
src: string | AudioBuffer;
hotkey?: string;
accent?: string;
}
export interface SystemAudioMixerProps {
/** Rows or console strips. Default `horizontal`. */
defaultOrientation?: Orientation;
/** Which sources to show. Default all four. */
sources?: MixerSourceId[];
/** Save mixer settings to localStorage under this key. */
persistKey?: string;
/** The mixed output, for recording or streaming. */
onOutputChange?: (stream: MediaStream | null) => void;
/** Tracks for the music channel. */
tracks?: MixerTrack[];
/** Sounds for the sounds channel. */
sounds?: MixerSound[];
className?: string;
}
const ALL_SOURCES: MixerSourceId[] = [
"microphone",
"system",
"music",
"sounds",
];
const NO_TRACKS: MixerTrack[] = [];
const NO_SOUNDS: MixerSound[] = [];
const CHANNELS = [
{ id: "microphone" },
{ gainDb: -6, id: "system" },
{ gainDb: -12, id: "music", monitor: true },
{ gainDb: -6, id: "sounds", monitor: true },
];
interface Status {
label: string;
tone: ChannelStripStatusProps["tone"];
}
const MixerPad = ({
sound,
bus,
}: {
sound: MixerSound;
bus: AudioNode | null;
}) => {
const player = useSound(sound.src, { destination: bus });
return (
player.play()}
playing={player.isPlaying}
size="sm"
>
{sound.label}
);
};
interface ChannelProps {
mixer: MixerController;
meter: FrameSource;
}
const microphoneStatus = (
microphone: UseMicrophoneResult,
audible: boolean
): Status => {
if (microphone.status === "active") {
return audible
? { label: "Live", tone: "live" }
: { label: "Muted", tone: "muted" };
}
if (microphone.status === "denied") {
return { label: "Blocked", tone: "error" };
}
return { label: "Off", tone: "default" };
};
const systemStatus = (system: UseSystemAudioResult): Status => {
if (system.status === "active") {
return { label: "On", tone: "live" };
}
if (system.status === "unsupported") {
return { label: "Unsupported", tone: "warning" };
}
return { label: "Off", tone: "default" };
};
const MicrophoneChannel = ({
microphone,
deviceId,
onDeviceChange,
mixer,
meter,
}: ChannelProps & {
microphone: UseMicrophoneResult;
deviceId: string | null;
onDeviceChange: (deviceId: string | null) => void;
}) => {
const devices = useAudioDevices();
const active = microphone.status === "active";
const deviceLabel =
devices.devices.find((device) => device.id === deviceId)?.label ??
"Default microphone";
return (
}
>
devices.requestPermission()}
onValueChange={onDeviceChange}
permission={
devices.permission === "unsupported"
? "denied"
: devices.permission
}
value={deviceId}
/>
>
}
description={active ? deviceLabel : "Not listening"}
icon={}
id="microphone"
meter={meter}
mixer={mixer}
notice={
microphone.status === "denied" ? (
Microphone access is blocked. Allow it in your browser's site
settings.
) : null
}
status={microphoneStatus(microphone, mixer.isAudible("microphone"))}
title="Microphone"
/>
);
};
const SystemChannel = ({
system,
mixer,
meter,
}: ChannelProps & { system: UseSystemAudioResult }) => {
const active = system.status === "active";
return (
checked ? system.start() : system.stop()
}
size="sm"
/>
}
description={active ? "Capturing" : "Share a screen or tab with audio"}
icon={}
id="system"
meter={meter}
mixer={mixer}
monitorable={false}
notice={
system.status === "no-audio" ? (
Nothing to hear: tick "Share audio" in the browser's
picker.
) : null
}
status={systemStatus(system)}
title="System audio"
/>
);
};
const MusicChannel = ({
player,
track,
trackCount,
onNext,
mixer,
meter,
}: ChannelProps & {
player: AudioPlayerController;
track: MixerTrack | undefined;
trackCount: number;
onNext: () => void;
}) => (
>
}
description={track ? track.title : "No tracks"}
icon={}
id="music"
meter={meter}
mixer={mixer}
status={player.playing ? { label: "Playing", tone: "live" } : undefined}
title="Music"
/>
);
const SoundsChannel = ({
sounds,
bus,
mixer,
meter,
}: ChannelProps & { sounds: MixerSound[]; bus: AudioNode | null }) => (
}
>
{sounds.map((sound) => (
))}
}
description={`${sounds.length} pads`}
icon={}
id="sounds"
meter={meter}
mixer={mixer}
title="Sounds"
/>
);
export const SystemAudioMixer = ({
defaultOrientation = "horizontal",
sources = ALL_SOURCES,
persistKey,
onOutputChange,
tracks = NO_TRACKS,
sounds = NO_SOUNDS,
className,
}: SystemAudioMixerProps) => {
const [orientation, setOrientation] =
useState(defaultOrientation);
const mixer = useMixer({ channels: CHANNELS, persistKey });
const [deviceId, setDeviceId] = useState(null);
const microphone = useMicrophone({ deviceId });
const system = useSystemAudio();
const [trackIndex, setTrackIndex] = useState(0);
const track = tracks[trackIndex];
const nextTrack = () =>
setTrackIndex((index) =>
tracks.length > 0 ? (index + 1) % tracks.length : 0
);
const player = useAudioPlayer({ onEnded: nextTrack, src: track?.src });
// Sound pads play into one bus so the mixer sees them as a single source.
const soundBus = useGainNode({ destination: null });
const graph = useWebAudioMixer(mixer, {
ducking: { targets: ["music"], trigger: "microphone" },
inputs: {
microphone: microphone.stream,
music: player.element,
sounds: soundBus,
system: system.stream,
},
});
// Fires when the stream changes, not on every render of the parent.
const emitOutput = useEffectEvent((stream: MediaStream | null) => {
onOutputChange?.(stream);
});
useEffect(() => {
emitOutput(graph.output);
}, [graph.output]);
const show = (id: MixerSourceId) => sources.includes(id);
const meterFor = (id: MixerSourceId) =>
graph.meters[id] ?? graph.master.meter;
return (
Audio mixer setOrientation(value as Orientation)}
value={orientation}
>
RowsConsole
{show("microphone") ? (
) : null}
{show("system") ? (
) : null}
{show("music") ? (
) : null}
{show("sounds") ? (
) : null}
No audio sources.
);
};
```
```tsx title="components/blocks/system-audio-mixer/mixer-source-strip.tsx"
"use client";
import { HeadphonesIcon } from "@phosphor-icons/react";
import type { ReactNode } from "react";
import {
ChannelStrip,
ChannelStripActions,
ChannelStripControls,
ChannelStripDescription,
ChannelStripFader,
ChannelStripHeader,
ChannelStripIcon,
ChannelStripMeter,
ChannelStripStatus,
ChannelStripText,
ChannelStripTitle,
ChannelStripValue,
} from "@/components/ui/channel-strip";
import type { ChannelStripStatusProps } from "@/components/ui/channel-strip";
import {
MonitorToggle,
MuteToggle,
SoloToggle,
} from "@/components/ui/channel-toggle";
import {
Fader,
FaderRange,
FaderThumb,
FaderTrack,
} from "@/components/ui/fader";
import { LevelMeter } from "@/components/ui/level-meter";
import type { Mixer } from "@/hooks/use-mixer";
import { formatDb } from "@/lib/audio/decibels";
import type { FrameSource, MeterFrame } from "@/lib/audio/types";
export interface MixerSourceStripProps {
id: string;
title: string;
description?: ReactNode;
icon: ReactNode;
accent?: string;
mixer: Mixer;
meter: FrameSource;
status?: { label: string; tone: ChannelStripStatusProps["tone"] };
/** Buttons in the header. */
actions?: ReactNode;
/** A ChannelStripNotice, shown under the strip. */
notice?: ReactNode;
/** Show the monitor toggle. Default true. */
monitorable?: boolean;
disabled?: boolean;
}
export const MixerSourceStrip = ({
id,
title,
description,
icon,
accent,
mixer,
meter,
status,
actions,
notice,
monitorable = true,
disabled = false,
}: MixerSourceStripProps) => {
const channel = mixer.channel(id);
if (!channel) {
return null;
}
return (
{icon}{title}
{description ? (
{description}
) : null}
{status ? (
{status.label}
) : null}
{actions ? {actions} : null}
mixer.setGain(id, gainDb)}
silenceAtMin
size="sm"
taper="audio"
value={channel.gainDb}
>
{formatDb(channel.gainDb, { floorDb: -60 })}
mixer.setMuted(id, muted)}
pressed={channel.muted}
size="sm"
>
M
mixer.setSolo(id, solo)}
pressed={channel.solo}
size="sm"
>
S
{monitorable ? (
mixer.setMonitor(id, monitor)}
pressed={channel.monitor}
size="sm"
>
) : null}
{notice}
);
};
```
```tsx title="components/blocks/system-audio-mixer/mixer-master-strip.tsx"
"use client";
import { SpeakerHighIcon } from "@phosphor-icons/react";
import {
ChannelStrip,
ChannelStripControls,
ChannelStripDescription,
ChannelStripFader,
ChannelStripHeader,
ChannelStripIcon,
ChannelStripMeter,
ChannelStripText,
ChannelStripTitle,
ChannelStripValue,
} from "@/components/ui/channel-strip";
import { MuteToggle } from "@/components/ui/channel-toggle";
import {
Fader,
FaderRange,
FaderThumb,
FaderTrack,
} from "@/components/ui/fader";
import {
LevelMeter,
LevelMeterBar,
LevelMeterChannel,
LevelMeterChannels,
LevelMeterClip,
LevelMeterHold,
LevelMeterTrack,
} from "@/components/ui/level-meter";
import type { Mixer } from "@/hooks/use-mixer";
import { formatDb } from "@/lib/audio/decibels";
import type { FrameSource, MeterFrame } from "@/lib/audio/types";
const CHANNELS = [0, 1];
export interface MixerMasterStripProps {
mixer: Mixer;
meter: FrameSource;
}
export const MixerMasterStrip = ({ mixer, meter }: MixerMasterStripProps) => (
MasterMix output
{CHANNELS.map((index) => (
))}
mixer.setMasterGain(value)}
silenceAtMin
size="sm"
taper="audio"
value={mixer.master.gainDb}
>
{formatDb(mixer.master.gainDb, { floorDb: -60 })}
mixer.setMasterMuted(value)}
pressed={mixer.master.muted}
size="sm"
>
M
);
```
# System Audio Settings (/docs/blocks/system-audio-settings)
```tsx title="components/examples/system-audio-settings-demo.tsx"
"use client";
import { SystemAudioSettings } from "@/components/blocks/system-audio-settings/system-audio-settings";
const SystemAudioSettingsDemo = () => (
);
export default SystemAudioSettingsDemo;
```
## Installation
```bash
npx shadcn@latest add @audiocn/system-audio-settings
```
## What it does
* A switch that opens the browser's screen-share picker and keeps only the audio.
* A state label: Off, On, Choose what to share, No audio shared, Ended, Needs permission or Unsupported.
* A level control (−24 to +12 dB, default −6 dB) and a stereo meter while capture is on.
* Notices that explain what gets captured, or why nothing can be.
Use `onStreamChange` to get the captured audio after the level control.
## Props
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `enabled / onEnabledChange` | `boolean` | — | Optional control of capture. |
| `gainDb / onGainChange` | `number` | `-6` | — |
| `onStreamChange` | `(stream: MediaStream \| null) => void` | — | The captured audio after the level control. |
## Files
```tsx title="components/blocks/system-audio-settings/system-audio-settings.tsx"
"use client";
import { DesktopIcon, InfoIcon, WarningIcon } from "@phosphor-icons/react";
import { useEffect, useEffectEvent, useId, useMemo, useState } from "react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Field,
FieldContent,
FieldDescription,
FieldGroup,
FieldLabel,
} from "@/components/ui/field";
import { LevelMeter } from "@/components/ui/level-meter";
import {
ParameterSlider,
ParameterSliderControl,
ParameterSliderHeader,
ParameterSliderInput,
ParameterSliderLabel,
ParameterSliderReset,
} from "@/components/ui/parameter-slider";
import { Switch } from "@/components/ui/switch";
import { useAudioAnalyser } from "@/hooks/use-audio-analyser";
import { useAudioContext } from "@/hooks/use-audio-context";
import { useGainNode } from "@/hooks/use-gain-node";
import { useSystemAudio } from "@/hooks/use-system-audio";
import type { SystemAudioStatus } from "@/hooks/use-system-audio";
import { dbToGain } from "@/lib/audio/decibels";
const DEFAULT_GAIN_DB = -6;
const STATE_LABELS: Record = {
active: "On",
denied: "Needs permission",
ended: "Ended",
idle: "Off",
"no-audio": "No audio shared",
prompting: "Choose what to share…",
unsupported: "Unsupported",
};
export interface SystemAudioSettingsProps {
enabled?: boolean;
onEnabledChange?: (enabled: boolean) => void;
gainDb?: number;
onGainChange?: (gainDb: number) => void;
/** The captured stream after the level control, for your own routing. */
onStreamChange?: (stream: MediaStream | null) => void;
className?: string;
}
export const SystemAudioSettings = ({
enabled: enabledProp,
onEnabledChange,
gainDb: gainDbProp,
onGainChange,
onStreamChange,
className,
}: SystemAudioSettingsProps) => {
const enabledId = useId();
const system = useSystemAudio();
const { context } = useAudioContext();
const [gainState, setGainState] = useState(DEFAULT_GAIN_DB);
const gainDb = gainDbProp ?? gainState;
const output = useMemo(
() => context?.createMediaStreamDestination() ?? null,
[context]
);
// The captured stream, through the level control, into a stream for the
// parent. Not routed to the speakers.
const gainNode = useGainNode({
destination: output,
gain: dbToGain(gainDb),
input: system.stream,
});
const analyser = useAudioAnalyser(system.stream ? gainNode : null, {
channels: "stereo",
});
const active = system.status === "active";
// A new callback each parent render must not re-emit the same stream.
const emitStream = useEffectEvent((stream: MediaStream | null) => {
onStreamChange?.(stream);
});
const processed =
context && gainNode && output && system.stream ? output.stream : null;
useEffect(() => {
emitStream(processed);
}, [processed]);
const { start: startCapture, stop: stopCapture } = system;
const isCapturing = useEffectEvent(
() => system.status === "active" || system.status === "prompting"
);
useEffect(() => {
if (enabledProp === true) {
if (!isCapturing()) {
startCapture();
}
} else if (enabledProp === false) {
stopCapture();
}
}, [enabledProp, startCapture, stopCapture]);
const setEnabled = (next: boolean) => {
onEnabledChange?.(next);
// Controlled, the effect above acts once the parent passes the new value.
// When the prop already says so (capture ended while `enabled` stayed
// true), nothing will change, so act here.
const propWillChange = enabledProp !== undefined && enabledProp !== next;
if (propWillChange) {
return;
}
if (next) {
system.start();
} else {
system.stop();
}
};
const setGain = (next: number) => {
setGainState(next);
onGainChange?.(next);
};
return (
System audio
Add the sound from your computer to your recording or stream.
Capture system audio
{STATE_LABELS[system.status]}
Your browser asks what to share. Choose a screen or tab and turn
on its audio.
Level
{active ? (
) : null}
{system.isSupported ? (
What gets captured
Everything the shared screen, window or tab plays. Some browsers
only offer tab audio.
) : (
Not available in this browser
This browser cannot capture system audio. Try a Chromium-based
browser.
)}
{system.status === "denied" ? (
Capture was not started
No screen or tab was shared. Turn capture on again and approve
the browser's sharing request. If access is blocked, allow
screen sharing in your browser or system settings.
) : null}
{system.status === "no-audio" ? (
No audio was shared
Turn capture on again and tick the option to share audio.
) : null}
);
};
```
# Audio Device Select (/docs/components/audio-device-select)
```tsx title="components/examples/audio-device-select-demo.tsx"
"use client";
import { useState } from "react";
import {
AudioDeviceSelect,
AudioDeviceSelectContent,
AudioDeviceSelectPreview,
AudioDeviceSelectTrigger,
AudioDeviceSelectValue,
} from "@/components/ui/audio-device-select";
import { LiveWaveform } from "@/components/ui/live-waveform";
import { useAudioAnalyser } from "@/hooks/use-audio-analyser";
import { useAudioDevices } from "@/hooks/use-audio-devices";
import { useMicrophone } from "@/hooks/use-microphone";
const AudioDeviceSelectDemo = () => {
const { devices, isLoading, permission, requestPermission } =
useAudioDevices();
const [deviceId, setDeviceId] = useState(null);
const microphone = useMicrophone({ deviceId, enabled: deviceId !== null });
const analyser = useAudioAnalyser(microphone.stream, { historySize: 120 });
return (
);
};
export default AudioDeviceSelectDemo;
```
## Installation
```bash
npx shadcn@latest add @audiocn/audio-device-select
```
## Usage
```tsx
import { AudioDeviceSelect } from "@/components/ui/audio-device-select";
```
```tsx
const { devices, permission, requestPermission } = useAudioDevices();
;
```
Devices come in as a prop, so the select works with [`useAudioDevices`](/docs/hooks/use-audio-devices) or with any device list, such as one from a native backend.
## Anatomy
```tsx
```
`AudioDeviceSelectContent` renders one item per device. Pass children to render items yourself with `AudioDeviceSelectItem`.
## Examples
### States
Selected device, a "None" option, a device that was unplugged, and loading.
```tsx title="components/examples/audio-device-select-states.tsx"
"use client";
import { AudioDeviceSelect } from "@/components/ui/audio-device-select";
import type { AudioDevice } from "@/components/ui/audio-device-select";
const devices: AudioDevice[] = [
{ id: "default", isDefault: true, label: "MacBook Pro Microphone" },
{ description: "USB", id: "usb", label: "Shure MV7+" },
{
description: "In use by another app",
id: "busy",
label: "Elgato Wave:3",
status: "unavailable",
},
];
const AudioDeviceSelectStates = () => (
);
export default AudioDeviceSelectStates;
```
## Behaviour
* A selected device that disappears is kept and shown as "(disconnected)", so the selection is never lost silently.
* Devices with `status` `unavailable` or `permission-required` are disabled.
* The default device is marked.
## Theming
| Data attribute | On | Meaning |
| ----------------- | ------- | ------------------------------- |
| `data-loading` | trigger | Devices are loading |
| `data-permission` | trigger | `granted`, `prompt` or `denied` |
| `data-missing` | trigger | The selected device is gone |
## API reference
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `devices` | `AudioDevice[]` | — | { id, label, isDefault?, status?, description? }. |
| `value` | `string \| null` | — | The device id. null is no selection, or None with allowNone. |
| `defaultValue` | `string \| null` | `null` | — |
| `onValueChange` | `(id: string \| null) => void` | — | — |
| `allowNone` | `boolean` | `false` | Adds a None item. |
| `noneLabel` | `string` | `"None"` | — |
| `loading` | `boolean` | `false` | Shows "Finding devices…". |
| `permission` | `"granted" \| "prompt" \| "denied"` | `"granted"` | — |
| `onRequestPermission` | `() => void` | — | Shows an "Allow access" button when permission is needed. |
| `disabled` | `boolean` | `false` | — |
# Audio Player (/docs/components/audio-player)
```tsx title="components/examples/audio-player-demo.tsx"
"use client";
import {
MusicNotesIcon,
PauseIcon,
PlayIcon,
SkipBackIcon,
SkipForwardIcon,
} from "@phosphor-icons/react";
import {
AudioPlayer,
AudioPlayerControls,
AudioPlayerDescription,
AudioPlayerPlay,
AudioPlayerSeek,
AudioPlayerSkipBack,
AudioPlayerSkipForward,
AudioPlayerTime,
AudioPlayerTitle,
AudioPlayerVolume,
} from "@/components/ui/audio-player";
import { useDemoTracks } from "@/lib/docs/use-demo-audio";
const AudioPlayerDemo = () => {
const [track] = useDemoTracks();
return (
{track?.title ?? "Loading…"}{track?.artist}
{({ playing }) =>
playing ? :
}
);
};
export default AudioPlayerDemo;
```
## Installation
```bash
npx shadcn@latest add @audiocn/audio-player
```
## Usage
```tsx
import {
AudioPlayer,
AudioPlayerPlay,
AudioPlayerSeek,
} from "@/components/ui/audio-player";
```
```tsx
```
Every part is optional. A play button and a seek bar is a complete player. Buttons show a text label unless you pass an icon as children, so the component works with any icon set.
## Anatomy
```tsx
```
## Examples
### Compact
```tsx title="components/examples/audio-player-compact.tsx"
"use client";
import { PauseIcon, PlayIcon } from "@phosphor-icons/react";
import {
AudioPlayer,
AudioPlayerPlay,
AudioPlayerRate,
AudioPlayerSeek,
AudioPlayerTime,
} from "@/components/ui/audio-player";
import { useDemoTracks } from "@/lib/docs/use-demo-audio";
const AudioPlayerCompact = () => {
const tracks = useDemoTracks();
const track = tracks.at(1);
return (
{({ playing }) =>
playing ? :
}
);
};
export default AudioPlayerCompact;
```
### With a waveform and a playlist
The [Music Player](/docs/blocks/music-player) block uses a [Waveform](/docs/components/waveform) as the seek bar and a [Track List](/docs/components/track-list) for the queue.
### Your own player state
Create the player with [`useAudioPlayer`](/docs/hooks/use-audio-player) and pass it in, to reach it from outside, route it into a mixer or analyse it.
```tsx
const player = useAudioPlayer({ src });
const analyser = useAudioAnalyser(player.element);
…;
```
`useAudioPlayerContext()` reads the player from inside any part.
## Keyboard
While focus is inside the player:
| Key | Action |
| -------------------- | ------------- |
| Space or K | Play or pause |
| Left / Right | Seek 5 s |
| Shift + Left / Right | Seek 15 s |
| Up / Down | Volume |
| M | Mute |
| Home / End | Start or end |
## Theming
| Data attribute | Meaning |
| --------------------------------------------------------------------------------------- | ------------------------- |
| `data-playing`, `data-paused`, `data-loading`, `data-ended`, `data-error`, `data-muted` | Player state, on the root |
## API reference
### AudioPlayer
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `src` | `string` | — | — |
| `player` | `AudioPlayerController` | — | Use an external player from useAudioPlayer. |
| `autoPlay / loop / muted` | `boolean` | `false` | — |
| `volume` | `number` | `1` | 0..1. |
| `playbackRate` | `number` | `1` | — |
| `preload` | `"none" \| "metadata" \| "auto"` | `"metadata"` | — |
| `crossOrigin` | `"anonymous" \| "use-credentials"` | — | Needed to analyse remote audio. |
| `onPlay / onPause / onEnded` | `() => void` | — | — |
| `onTimeUpdate` | `(time) => void` | — | — |
| `onPrevious / onNext` | `() => void` | — | Enable the previous and next buttons. |
| `onError` | `(error: MediaError \| null) => void` | — | — |
| `shortcuts` | `boolean` | `true` | Keyboard shortcuts while focus is inside. |
### AudioPlayerPlay
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode \| ({ playing, loading }) => ReactNode` | — | An icon, or a function of the state. |
### AudioPlayerSkipBack, AudioPlayerSkipForward
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `seconds` | `number` | `10` | — |
### AudioPlayerTime
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `type` | `"current" \| "remaining" \| "duration"` | `"current"` | — |
| `format` | `(seconds, type) => string` | `formatTime` | — |
### AudioPlayerRate
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `rates` | `number[]` | `[0.5, 0.75, 1, 1.25, 1.5, 2]` | Cycles on click. |
# Bar Visualizer (/docs/components/bar-visualizer)
```tsx title="components/examples/bar-visualizer-demo.tsx"
"use client";
import { BarVisualizer } from "@/components/ui/bar-visualizer";
import { useDemoSignal } from "@/hooks/use-demo-signal";
const BarVisualizerDemo = () => {
const signal = useDemoSignal({ kind: "speech" });
return (
);
};
export default BarVisualizerDemo;
```
## Installation
```bash
npx shadcn@latest add @audiocn/bar-visualizer
```
## Usage
```tsx
import { BarVisualizer } from "@/components/ui/bar-visualizer";
```
```tsx
```
Bars take their color from the text color, so set it with a class such as `text-primary`. Bars paint on the animation frame without re-rendering React.
## Examples
### Alignment
```tsx title="components/examples/bar-visualizer-align.tsx"
"use client";
import { BarVisualizer } from "@/components/ui/bar-visualizer";
import { useDemoSignal } from "@/hooks/use-demo-signal";
const alignments = ["center", "end", "start"] as const;
const BarVisualizerAlign = () => {
const signal = useDemoSignal({ kind: "music" });
return (
{alignments.map((align) => (
{align}
))}
);
};
export default BarVisualizerAlign;
```
### Idle and loading
`idle` decides what bars do without a signal. `loading` runs a sweep, for connecting or thinking states.
```tsx title="components/examples/bar-visualizer-states.tsx"
import { BarVisualizer } from "@/components/ui/bar-visualizer";
const BarVisualizerStates = () => (
idle pulse
idle wave
loading
);
export default BarVisualizerStates;
```
### Mirrored
```tsx title="components/examples/bar-visualizer-mirrored.tsx"
"use client";
import { BarVisualizer } from "@/components/ui/bar-visualizer";
import { useDemoSignal } from "@/hooks/use-demo-signal";
const BarVisualizerMirrored = () => {
const signal = useDemoSignal({ kind: "speech", seed: 8 });
return (
);
};
export default BarVisualizerMirrored;
```
### Inside a badge
```tsx title="components/examples/bar-visualizer-mini.tsx"
"use client";
import { MicrophoneIcon } from "@phosphor-icons/react";
import { Badge } from "@/components/ui/badge";
import { BarVisualizer } from "@/components/ui/bar-visualizer";
import { useDemoSignal } from "@/hooks/use-demo-signal";
const BarVisualizerMini = () => {
const signal = useDemoSignal({ kind: "speech", seed: 12 });
return (
Live
);
};
export default BarVisualizerMini;
```
## Theming
| Variable or attribute | Meaning |
| --------------------- | ---------------------------------------- |
| `--bar-width` | Maximum bar width, default `0.375rem` |
| `--bar-gap` | Gap between bars, default `0.1875rem` |
| `--bar-radius` | Bar corner radius, default fully rounded |
| `data-active` | The signal is above the floor |
| `data-loading` | The sweep is running |
| `data-index` | On each bar, its position |
## Accessibility
The root has `role="img"` and the label "Audio visualizer". Pass `aria-label` to describe what it shows, or `aria-hidden` when it is decorative next to a labelled meter.
## API reference
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `source` | `FrameSource \| null` | — | Bars follow the frame's frequency bands. |
| `levels` | `ArrayLike` | — | Levels, 0..1, for declarative use. |
| `barCount` | `number` | `24` | Bands are resampled to fit. |
| `align` | `"center" \| "start" \| "end"` | `"center"` | Where bars grow from. |
| `mirrored` | `boolean` | `false` | Symmetric around the middle bar, lows in the centre. |
| `minLevel` | `number` | `0.08` | Resting bar size, 0..1. |
| `idle` | `"static" \| "pulse" \| "wave"` | `"static"` | What bars do without a signal. |
| `loading` | `boolean` | `false` | Run a sweep animation. |
| `orientation` | `"horizontal" \| "vertical"` | `"horizontal"` | vertical grows bars sideways. |
| `actionsRef` | `Ref` | — | { paint(levels) }. |
# Channel Strip (/docs/components/channel-strip)
```tsx title="components/examples/channel-strip-demo.tsx"
"use client";
import { MicrophoneIcon } from "@phosphor-icons/react";
import { useState } from "react";
import {
ChannelStrip,
ChannelStripControls,
ChannelStripDescription,
ChannelStripFader,
ChannelStripHeader,
ChannelStripIcon,
ChannelStripMeter,
ChannelStripStatus,
ChannelStripText,
ChannelStripTitle,
ChannelStripValue,
} from "@/components/ui/channel-strip";
import { MuteToggle, SoloToggle } from "@/components/ui/channel-toggle";
import { DbReadout } from "@/components/ui/db-readout";
import { Fader } from "@/components/ui/fader";
import { LevelMeter } from "@/components/ui/level-meter";
import { useDemoSignal } from "@/hooks/use-demo-signal";
const ChannelStripDemo = () => {
const [gainDb, setGainDb] = useState(0);
const [muted, setMuted] = useState(false);
const [solo, setSolo] = useState(false);
const signal = useDemoSignal({ gainDb, kind: "speech", playing: !muted });
return (
MicrophoneShure MV7+
{muted ? "Muted" : "Live"}
M
S
);
};
export default ChannelStripDemo;
```
In these previews, the fader applies gain to the demo signal and mute silences it. The meter shows the level after both controls. Muting or excluding a channel with solo clears its meter immediately; audible channels keep their normal meter ballistics.
## Installation
```bash
npx shadcn@latest add @audiocn/channel-strip
```
`channel-strip` is layout and context only. Install the meters, faders and toggles you put inside it separately, or install a [block](/docs/blocks/system-audio-mixer) that brings everything.
## Usage
```tsx
import {
ChannelStrip,
ChannelStripHeader,
ChannelStripMeter,
ChannelStripTitle,
} from "@/components/ui/channel-strip";
```
```tsx
Microphone
```
Every part is optional. The smallest useful strip is a title, a meter and a mute toggle.
## Anatomy
```tsx
```
## Examples
### Console strips
With `orientation="vertical"`, the meter and fader stand side by side. These strips share `useMixer` state, so solo silences the other channels.
```tsx title="components/examples/channel-strip-console.tsx"
"use client";
import {
DesktopIcon,
MicrophoneIcon,
MusicNotesIcon,
} from "@phosphor-icons/react";
import type { ReactNode } from "react";
import {
ChannelStrip,
ChannelStripControls,
ChannelStripFader,
ChannelStripHeader,
ChannelStripIcon,
ChannelStripMeter,
ChannelStripTitle,
ChannelStripValue,
} from "@/components/ui/channel-strip";
import { MuteToggle, SoloToggle } from "@/components/ui/channel-toggle";
import { Fader } from "@/components/ui/fader";
import { LevelMeter } from "@/components/ui/level-meter";
import { useDemoSignal } from "@/hooks/use-demo-signal";
import type { DemoSignalKind } from "@/hooks/use-demo-signal";
import { useMixer } from "@/hooks/use-mixer";
import type { Mixer } from "@/hooks/use-mixer";
import { formatDb } from "@/lib/audio/decibels";
const INITIAL_CHANNELS = [{ id: "mic" }, { id: "music" }, { id: "game" }];
const Strip = ({
id,
mixer,
title,
icon,
accent,
kind,
seed,
}: {
id: string;
mixer: Mixer;
title: string;
icon: ReactNode;
accent: string;
kind: DemoSignalKind;
seed?: number;
}) => {
const channel = mixer.channel(id);
const signal = useDemoSignal({
channels: 2,
gainDb: channel?.gainDb,
kind,
playing: mixer.isAudible(id),
seed,
});
if (!channel) {
return null;
}
return (
{icon}{title} mixer.setGain(id, gainDb)}
size="sm"
taper="audio"
value={channel.gainDb}
/>
{formatDb(channel.gainDb)} mixer.setMuted(id, muted)}
pressed={channel.muted}
size="sm"
>
M
mixer.setSolo(id, solo)}
pressed={channel.solo}
size="sm"
>
S
);
};
const ChannelStripConsole = () => {
const mixer = useMixer({ channels: INITIAL_CHANNELS });
return (
MicrophoneBlocked
Microphone access is blocked. Allow it in your browser's site
settings.
System audioPaused
Paused to prevent an echo from your own stream.
);
export default ChannelStripNotices;
```
## How it passes settings down
A strip provides its `orientation`, `size` and `disabled` state to the audiocn components inside it, so meters and faders line up without extra props. When the strip is `muted` or `dimmed`, meters inside it render dimmed. Explicit props on a child always win. `useChannelStrip()` reads the strip's state in your own parts.
## Layout
Parts place themselves on a CSS grid by area name: `header`, `meter`, `fader`, `value`, `controls` and `notice`. The grid is the strip's `channel-strip-layout` element, so you can rearrange a strip by overriding `grid-template-areas` there, for example with `*:data-[slot=channel-strip-layout]:[grid-template-areas:…]`.
A row measures its own width with a container query. Below 36rem it puts the header on its own line, with the meter and fader full width underneath, so rows stay readable on phones and in narrow panels. From 36rem up the header sits beside the meter in a column `--channel-strip-header-width` wide. Set that variable on a mixer to align every row; the header wraps its status and actions onto a second line before it truncates the title.
`ChannelStripFader` removes the fader's end padding so its track and scale reach the meter's edges in both orientations. At minimum and maximum, the thumb's centre aligns with the track edge. For track-only faders, strips centre the visible meter and fader tracks as a group in both orientations, while keeping the fader's full thumb and pointer target.
Horizontal strips reserve a notice row only when you include `ChannelStripNotice`, so strips without a notice keep equal top and bottom spacing.
`ChannelStripValue` centres its content in vertical strips and aligns it to the right in horizontal strips.
A vertical strip keeps its width inside a mixer. When the strips do not fit, the mixer's channels scroll instead of squeezing them.
## Theming
| Variable or attribute | Meaning |
| -------------------------------------------------------------------------- | -------------------------------------------- |
| `--channel-accent` | Set by `accent`, drawn as a colour tag |
| `--channel-strip-width` | Width of a vertical strip, default `6.5rem` |
| `--channel-strip-header-width` | Header column of a wide row, default `12rem` |
| `data-muted`, `data-solo`, `data-dimmed`, `data-selected`, `data-disabled` | Channel state |
| `data-clipping` | A meter inside the strip is clipping |
| `data-orientation`, `data-variant`, `data-size` | Current settings |
## Accessibility
The strip is a `group` named by `ChannelStripTitle`. A notice is a `status`, or an `alert` for the `destructive` variant. State is never shown by colour alone: pair a muted strip with a pressed mute toggle and a status label.
## API reference
### ChannelStrip
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `orientation` | `"horizontal" \| "vertical"` | `from Mixer` | Horizontal is a row; vertical is a console strip. |
| `variant` | `"default" \| "card" \| "ghost" \| "master"` | `"default"` | — |
| `size` | `"sm" \| "default" \| "lg"` | `from Mixer` | Passed to controls inside. |
| `muted` | `boolean` | `false` | Styling and context only. |
| `solo` | `boolean` | `false` | — |
| `dimmed` | `boolean` | `false` | Silenced by another channel's solo. |
| `selected` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | Disables every control inside. |
| `accent` | `string` | — | A CSS colour for the colour tag. |
| `render` | `ReactElement \| function` | `
);
};
export default ChannelToggleDemo;
```
## Installation
```bash
npx shadcn@latest add @audiocn/channel-toggle
```
## Usage
```tsx
import {
MonitorToggle,
MuteToggle,
SoloToggle,
} from "@/components/ui/channel-toggle";
```
```tsx
MS
```
The presets set the tone and a default `aria-label`. Children are a letter, a word or an icon; nothing is rendered by default. Use `ChannelToggle` with a `tone` for anything else.
## Examples
### Variants
```tsx title="components/examples/channel-toggle-variants.tsx"
"use client";
import { MicrophoneSlashIcon } from "@phosphor-icons/react";
import { ChannelToggle, MuteToggle } from "@/components/ui/channel-toggle";
const variants = ["default", "outline", "ghost"] as const;
const ChannelToggleVariants = () => (
);
};
export default ClipIndicatorDemo;
```
## Installation
```bash
npx shadcn@latest add @audiocn/clip-indicator
```
## Usage
```tsx
import { ClipIndicator } from "@/components/ui/clip-indicator";
```
```tsx
```
The light turns on when any channel reaches −1 dBFS and stays on for 1.5 s. Clicking it resets the light and the count. Its size never changes, so turning on never moves the layout.
## Examples
### Latching, driven by hand
Set `holdMs` to `Infinity` to keep the light on until someone resets it. Use `actionsRef` to report levels from your own code.
```tsx title="components/examples/clip-indicator-latching.tsx"
"use client";
import { useRef } from "react";
import { Button } from "@/components/ui/button";
import { ClipIndicator } from "@/components/ui/clip-indicator";
import type { ClipIndicatorActions } from "@/components/ui/clip-indicator";
const ClipIndicatorLatching = () => {
const clip = useRef(null);
return (
);
};
export default ClipIndicatorLatching;
```
### Controlled
Pass `clipping` when another part of your app decides whether the signal clipped.
```tsx
```
## Theming
| Token or attribute | Meaning |
| ------------------ | -------------------------- |
| `--meter-clip` | Color of the light when on |
| `data-clipping` | The light is on |
Children replace the default dot, so the light can be a word, an icon or anything else. Use `group-data-clipping/clip-indicator:` to style children.
## Accessibility
* A real `