Lab

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

pnpm dlx shadcn@latest add @audio-ui/use-microphone
import { useMicrophone, useMicrophoneSwitch, usePageMicrophone } from "@/hooks/use-microphone";
Fileshooks/use-microphone.ts
Depends onweb-audio, use-audio-session
npmNothing
Used byneedle-meter-demo, tuner
ExportKindWhat it is
UseMicrophoneReturninterface
useMicrophonefunctionThe microphone as an AnalyserNode on the shared AudioContext.
useMicrophoneSwitchfunctionThe microphone switch of the nearest session: a button in its bar flips it, and every component inside the session that listens with usePageMicrophone follows.
usePageMicrophonefunctionThe 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.

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, or the pitch a Tuner shows.

Returns · 5

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