useMicrophone
Open a microphone as a MediaStream, with browser processing off by default.
$ pnpm dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-microphone.json$ npx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-microphone.json$ yarn dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-microphone.json$ bunx --bun shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-microphone.jsonUsage
<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
| Prop | Type | Default |
|---|---|---|
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. | boolean | false |
echoCancellation Browser echo cancellation. | boolean | false |
noiseSuppression Browser noise suppression. | boolean | false |
autoGainControl Browser automatic gain control. | boolean | false |
channelCount Requested channel count. | number | — |
Returns
| Prop | Type | Default |
|---|---|---|
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 | — |