useAudioDevices
The list of audio input or output devices, with permission state and live updates.
$ pnpm dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-devices.json$ npx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-devices.json$ yarn dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-devices.json$ bunx --bun shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-devices.jsonUsage
<script lang="ts">
import { AudioDeviceSelect } from "#lib/components/ui/audio-device-select/index.js";
import { Button } from "#lib/components/ui/button/index.js";
import { useAudioDevices } from "#lib/hooks/use-audio-devices.svelte.js";
const audio = useAudioDevices();
let deviceId = $state<string | null>(null);
</script>
{#if audio.permission === "prompt"}
<Button onclick={audio.requestPermission}>Allow microphone access</Button>
{:else}
<AudioDeviceSelect devices={audio.devices} bind:value={deviceId} />
{/if}Call it during component setup. The fields are getters, so read them from the returned object, such as audio.devices; destructuring them loses updates. The options can be a getter, such as () => ({ kind }).
Browsers hide device names until the page has microphone access. Until then devices are labelled "Microphone 1", "Microphone 2" and so on.
Options
| Prop | Type | Default |
|---|---|---|
kind Which devices to list. | "audioinput" | "audiooutput" | "audioinput" |
Returns
| Prop | Type | Default |
|---|---|---|
devices { id, label, kind, groupId, isDefault }. Updates when devices are plugged in or removed. | AudioDeviceInfo[] | — |
permission Microphone permission. | "granted" | "prompt" | "denied" | "unsupported" | — |
isLoading True until the first list arrives. | boolean | — |
error The last error. | Error | null | — |
refresh List devices again. | () => Promise<void> | — |
requestPermission Ask for microphone access so labels become readable. | () => Promise<boolean> | — |