Lab

AudioSessionProvider

A session of its own for a demo and its controls: a play switch and a microphone switch that nothing outside it follows. Holds no audio, so two previews on a page never play together. Outside a session the switches stay off.

pnpm dlx shadcn@latest add @audio-ui/use-audio-session
import { silentPlay, silentMicrophone, silentSource, createAudioSession, AudioSessionProvider, /* … */ } from "@/hooks/use-audio-session";
Fileshooks/use-audio-session.tsx
Depends onNothing
npmNothing
Used byuse-demo-source, use-microphone, use-play-switch
ExportKindWhat it is
PlayStatetype
MicrophoneStatetype
SourceStatetypeThe sound a preview plays: the one a person chose, and the one the device plays when nobody has.
silentPlayconst
silentMicrophoneconst
silentSourceconstA source store that does nothing and stays empty: what a component reads when there is no session around it.
AudioSessioninterfaceWhat one preview shares between its bar and the demo it shows: whether the sound should play, whether the microphone should listen, and which sound is played.
createAudioSessionfunction
AudioSessionProviderfunctionGives what is inside it a session of its own: a play switch and a microphone switch and a sound to play that nothing outside it follows.
useAudioSessionfunctionThe nearest session, or nothing when the component is not inside one.

Usage

What one preview shares between its bar and the demo it shows: whether the sound should play, whether the microphone should listen, and which sound is played. It holds no audio, only those, so two sessions on a page never touch each other.

import { AudioSessionProvider } from "@/hooks/use-audio-session";
import { usePlaySwitch } from "@/hooks/use-play-switch";

function PlayButton() {
  const { playing, toggle } = usePlaySwitch();
  return <Button onClick={toggle}>{playing ? "Stop" : "Play"}</Button>;
}

<AudioSessionProvider>
  <PlayButton />
  <BlockCompressor />
</AudioSessionProvider>;

Inside one, usePlaySwitch, the microphone switch of useMicrophone and useDemoSource follow it; outside one they stay off. A switch turns off when the last control showing it goes.

Built by Ouest Labs, the source code is available on GitHub.
RSS