audiocn-svelte
Esc

Start typing to search the docs

useMicrophone

Open a microphone as a MediaStream, with browser processing off by default.

2 min read · 217 words

$ pnpm dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-microphone.json

Usage

<script lang="ts">
	import { Button } from "#lib/components/ui/button/index.js";
	import { useAudioAnalyser } from "#lib/hooks/use-audio-analyser.svelte.js";
	import { useMicrophone } from "#lib/hooks/use-microphone.svelte.js";

	let { deviceId }: { deviceId: string | null } = $props();

	const microphone = useMicrophone(() => ({ deviceId }));
	const analyser = useAudioAnalyser(() => microphone.stream);
</script>

<Button onclick={microphone.start}>Start</Button>

Call it during component setup. Pass the options as a getter, as above, so a new deviceId reopens the stream. stream, status and error are getters: read them from the returned object, and pass () => microphone.stream to other hooks. start() and stop() override enabled until it changes.

Echo cancellation, noise suppression and automatic gain control are off by default. Browsers turn them on for calls, but they change the level a meter shows. Turn them on when you want call-style audio.

Options

PropTypeDefault
deviceId

The device to open. Omit for the system default. Changing it reopens the stream.

string | null—
enabled

Open the microphone as soon as possible.

booleanfalse
echoCancellation

Browser echo cancellation.

booleanfalse
noiseSuppression

Browser noise suppression.

booleanfalse
autoGainControl

Browser automatic gain control.

booleanfalse
channelCount

Requested channel count.

number—

Returns

PropTypeDefault
stream

The open stream.

MediaStream | null—
status

unavailable also covers a device that was unplugged.

"idle" | "acquiring" | "active" | "denied" | "unavailable" | "error"—
error

The last error.

Error | null—
start

Open the microphone.

() => Promise<void>—
stop

Close it and release the device.

() => void—
Last updated on October 7, 2026