# useMicrophone

> The microphone as an AnalyserNode on the shared AudioContext: raw signal, never connected to the speakers, released on stop and on unmount. The session's switch, usePageMicrophone, lets a button turn it on for a demo

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

```ts
import { useMicrophone, useMicrophoneSwitch, usePageMicrophone } from "@/hooks/use-microphone";
```

- Files: `hooks/use-microphone.ts`
- Depends on: `web-audio`, `use-audio-session`; npm: nothing
- Used by: `needle-meter-demo`, `tuner`

| Export | Kind | What it is |
| --- | --- | --- |
| `UseMicrophoneReturn` | interface |  |
| `useMicrophone` | function | The microphone as an `AnalyserNode` on the shared AudioContext. |
| `useMicrophoneSwitch` | function | The microphone switch of the nearest session: a button in its bar flips it, and every component inside the session that listens with `usePageMicrophone` follows. |
| `usePageMicrophone` | function | The microphone while the session's switch is on, as an `AnalyserNode` to read (`null` while it is off). |

## Usage

`useMicrophone` taps the microphone into an `AnalyserNode` on the page's audio context. The signal is raw: echo cancellation, noise suppression and automatic gain are off, since they flatten a tuner or a meter. The analyser is never connected to the speakers.

```tsx
import { useMicrophone } from "@/hooks/use-microphone";

const mic = useMicrophone();
// Memoized: a new array restarts the sampling.
const analysers = useMemo(() => (mic.analyser ? [mic.analyser] : []), [mic.analyser]);
const levels = useAudioLevels(analysers);

<button onClick={mic.isListening ? mic.stop : mic.start} type="button">
  {mic.isListening ? "Stop" : "Listen"}
</button>
<Meter aria-label="Microphone" source={levels} />
```

Give the analyser to anything that reads one: [levels and spectra](/docs/guides/analysis), or the pitch a [Tuner](/docs/components/base/tuner) shows.

**Returns**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `start` | `() => Promise<void>` |  | Asks for the microphone and listens. Call it from a click. |
| `stop` | `() => void` |  | Releases the microphone. Unmounting does too. |
| `analyser` | `AnalyserNode \| null` |  | The signal while it listens, `null` otherwise. |
| `isListening` | `boolean` |  | Whether it listens. |
| `error` | `string \| null` |  | Why it could not listen, such as a refused permission. |
