# 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.

```bash
npx shadcn@latest add @audio-ui/use-audio-session
```

```ts
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.

```tsx
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`](/docs/hooks/use-play-switch), the microphone switch of [`useMicrophone`](/docs/hooks/use-microphone) and [`useDemoSource`](/docs/hooks/use-demo-source) follow it; outside one they stay off. A switch turns off when the last control showing it goes.
