pnpm dlx shadcn@latest add @audio-ui/use-microphone
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.
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
Asks for the microphone and listens. Call it from a click.
Releases the microphone. Unmounting does too.
The signal while it listens,
null otherwise.Whether it listens.
Why it could not listen, such as a refused permission.