pnpm dlx shadcn@latest add @audio-ui/use-audio-session
import { silentPlay, silentMicrophone, silentSource, createAudioSession, AudioSessionProvider, /* … */ } from "@/hooks/use-audio-session";| Files | hooks/use-audio-session.tsx |
|---|---|
| Depends on | Nothing |
| npm | Nothing |
| Used by | use-demo-source, use-microphone, use-play-switch |
| Export | Kind | What it is |
|---|---|---|
PlayState | type | |
MicrophoneState | type | |
SourceState | type | The sound a preview plays: the one a person chose, and the one the device plays when nobody has. |
silentPlay | const | |
silentMicrophone | const | |
silentSource | const | A source store that does nothing and stays empty: what a component reads when there is no session around it. |
AudioSession | interface | 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. |
createAudioSession | function | |
AudioSessionProvider | function | Gives 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. |
useAudioSession | function | The 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.