Skip to content

shadcn.io is an independent project built on shadcn/ui

Components

Free

Mic Selector for UI SDK

A searchable list of the microphones plugged in, kept current as they come and go. For React on UI SDK, to pick the one a recording uses.

On this page12 sections

Mic Selector is a button that shows which microphone a recording will use and opens a searchable list of every audio input the browser sees. Reach for it before recording, when someone may have a laptop mic, a headset and a webcam at once and the system default isn't the one they speak into.

The list follows the hardware as it's plugged in and out. It's a Popover holding a Command, and it hands you the chosen deviceId. Recording from it is your code's job.

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

Anatomy

Mic Selector anatomy: trigger, value, content, input, list, item, label

Usage

import { MicIcon } from "lucide-react";
import { useState } from "react";
import {
  MicSelector, MicSelectorContent, MicSelectorEmpty, MicSelectorInput,
  MicSelectorList, MicSelectorTrigger, MicSelectorValue,
} from "@/components/ui/mic-selector";
export function MicrophonePicker() {
  const [deviceId, setDeviceId] = useState<string>();

  return (
    <MicSelector onValueChange={setDeviceId} value={deviceId}>
      <MicSelectorTrigger className="w-full">
        <MicIcon aria-hidden="true" />
        <MicSelectorValue />
      </MicSelectorTrigger>
      <MicSelectorContent>
        <MicSelectorInput />
        <MicSelectorList>
          <MicSelectorEmpty />
        </MicSelectorList>
      </MicSelectorContent>
    </MicSelector>
  );
}

MicSelectorList renders one item per microphone by itself, so its only child is MicSelectorEmpty, which shows when the search matches nothing. The value is the picked microphone's deviceId.

Accessibility

The trigger is a button whose name is the microphone it shows, or the placeholder, and it opens a popover with focus in the search field. The arrow keys move a highlight through the microphones while focus stays in the field, and picking one closes the popover and returns focus to the trigger. The selected microphone reports aria-current. The popover is named Microphone for screen readers, or whatever you set as title on MicSelectorContent. Because the trigger names only the device, put a visible label such as Microphone beside it.

Enter
On the trigger, opens the list. In the search field, picks the highlighted microphone and closes the list, or on the Allow microphone access row, asks for access and keeps the list open.
Space
On the trigger, opens the list.
Arrow Down
Highlights the next microphone, and stays on the last one.
Arrow Up
Highlights the previous microphone, and stays on the first one.
Ctrl+N
On a Mac, highlights the next microphone, as ArrowDown does.
Ctrl+P
On a Mac, highlights the previous microphone, as ArrowUp does.
Page Down
Moves the highlight ten rows down, or to the last row.
Page Up
Moves the highlight ten rows up, or to the first row.
Escape
Clears the search field. When it's already empty, closes the list without a change and returns focus to the trigger.

Microphone access

Listing the microphones asks for nothing, but browsers hide their names until the page may use the microphone. Until then the list starts with an Allow microphone access row, and picking it shows the browser's prompt. Once the person allows it, the row goes and the list fills with every microphone by name. Neither loading the page nor opening the list prompts on its own.

Record from the chosen microphone by its deviceId:

const stream = await navigator.mediaDevices.getUserMedia({
  audio: { deviceId: { exact: deviceId } },
});

A name that ends with a USB vendor and product id, such as Yeti Stereo Microphone (046d:0ab7), shows the id muted after the name, and a device with no name at all shows as Unknown microphone, or the unknownLabel you set on MicSelector.

Demos

Devices

Five microphones of your own, a MacBook's built-in mic listed twice, a Yeti, AirPods and a webcam, passed as devices instead of the browser's, with the Yeti selected and a line under the trigger naming it. Pass a list like this in tests, previews and screenshots where there's no hardware. Each entry needs a deviceId and a label, which a browser's MediaDeviceInfo already has.

Preview width

Input level

Picking a microphone here opens that one alone, with getUserMedia and the picked deviceId as exact, and a bar under the trigger follows how loud it is. Picking another closes the first before opening the next. Start from this when you record or stream from the person's choice, and stop the tracks when they pick again or leave.

Preview width

Audio devices

A status line under the trigger reads useAudioDevices from inside MicSelector and says how many microphones the browser lists, or why it couldn't list them. Until access is allowed, a Show their names button beside it calls loadDevices, the same request the Allow microphone access row makes. Use the hook for a part of your own, such as a count or a setup screen's access button.

Preview width

Labels

The same picker in French. placeholder on MicSelectorValue and MicSelectorInput, permissionLabel and errorLabel on MicSelectorList, unknownLabel on MicSelector, title on MicSelectorContent and the children of MicSelectorEmpty cover every word, the ones only screen readers hear included. The popover renders outside the page's French wrapper, so MicSelectorContent takes lang too.

Preview width

Reading devices with useAudioDevices

Called inside a MicSelector, the hook returns the browser's microphones, even when a devices prop replaces them in the list.

FieldWhat it is
devicesThe audio inputs as MediaDeviceInfo, listed again on every devicechange
hasPermissionWhether the page may use the microphone, so the devices have names
loadDevicesAsks for the microphone, then lists the devices again with their names
loadingWhether they're being listed
errorWhy they couldn't be listed or access was refused, else null

Migrating from AI SDK Elements

If you added Mic Selector from AI SDK Elements (opens in a new tab), install this one and change the import from @/components/ai-elements/mic-selector to @/components/ui/mic-selector. The parts keep their names, and value, defaultValue, onValueChange, open and onOpenChange work the same. What differs:

  • MicSelectorList takes no function. Drop {(devices) => …} and keep <MicSelectorEmpty /> as its child, since it renders a MicSelectorItem and MicSelectorLabel per microphone itself.
  • Opening the list doesn't ask for the microphone. The Allow microphone access row does.
  • useAudioDevices returns the same fields, but reads the MicSelector around it instead of standing alone.
  • MicSelectorContent's props go to the popover, and popoverOptions is gone. It matches the trigger's width without a ResizeObserver.

FAQ

Why does Mic Selector show Allow microphone access instead of my microphones?

Browsers keep microphones' names from a page, and often the microphones themselves, until it may use one. Mic Selector lists only devices the browser gives an id, and until one of them has a name, it shows the Allow microphone access row first.

Pick the row and allow access in the browser's prompt, and the list fills in. Once access is allowed, for this visit or for good, the row is gone.

What happens in Mic Selector when someone blocks microphone access?

The Allow microphone access row turns into Couldn't access the microphone, and picking it asks again. A browser that remembers the refusal turns that request down without showing its prompt, so the row stays as it is. Set its text with errorLabel on MicSelectorList.

To say why, read error and hasPermission from useAudioDevices, as the Audio devices demo does, and when access was refused, tell people to allow the microphone in the browser's site settings and try again.

How do I record from the microphone picked in Mic Selector?

Take the picked deviceId from the value and pass it to getUserMedia as audio: { deviceId: { exact: deviceId } }, as the Input level demo does. With exact, the call fails when that microphone is unplugged, instead of quietly recording from another one.

The browser keeps a microphone's id stable for your site until the person clears its data, so save it and set it as the value on the next visit.

Does Mic Selector update when a microphone is plugged in?

Yes. It lists the devices again on the browser's devicechange event, so a headset plugged in or out appears or goes while the page is open, with no reload.

When the selected microphone is unplugged, the trigger shows the placeholder, but the value keeps its deviceId and nothing calls your change handler. Plug it back in and the trigger names it again.

Why does Mic Selector list the same microphone twice in Chrome?

Chrome adds an entry for the system default, with the id default and a name such as Default - MacBook Pro Microphone, beside the device's own entry. On Windows it adds a Communications entry too. Picking Default follows whatever the system's default is later, while the device's own entry stays on that microphone.

Mic Selector shows what the browser returns and has no option to hide entries. To drop them, list the devices yourself with enumerateDevices, filter them and pass the rest as devices.

How do I show Mic Selector without real microphones?

Pass devices, an array of objects with a deviceId and a label, as the Devices demo does. The list shows those instead of the browser's and skips the Allow microphone access row.

That suits tests, screenshots and docs, where there's no hardware, and a list you keep yourself. Because the access row goes, ask for the microphone some other way, such as a button that calls loadDevices.

Can Mic Selector be used with the keyboard?

Yes. Enter or Space on the trigger opens the list with focus in the search field. Typing filters by name, the arrow keys move through the microphones, Enter picks one, and Escape clears the search, then closes the list, returning focus to the trigger.

The Accessibility section lists each key on your library.

Is this the same as AI SDK Elements' Mic Selector?

It has the same parts and props, so most code only changes its import. The list renders its own items instead of taking a function, and it asks for the microphone from a row rather than when it opens. The Migrating section lists every difference.

API Reference

MicSelector

PropType
open?boolean

Whether it's open (controlled).

defaultOpen?boolean

Whether it starts open, when uncontrolled.

Default
false
onOpenChange?(open: boolean) → void

Called when it opens or closes.

Parameters

open – boolean

Returns
void
value?string

The selected microphone's deviceId (controlled).

defaultValue?string

The microphone selected at first, when uncontrolled: its deviceId.

onValueChange?(value: string) → void

Called with the deviceId of the microphone picked.

Parameters

value – string

Returns
void
closeDelay?number

Milliseconds before the popover closes once the pointer leaves it and its trigger, with openOnHover.

Default
0
container?DocumentFragment | Element | null

Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.

Type
DocumentFragment | Element | null
controller?PopupController<any, PopoverOpenChangeReason, {}, string, PopoverPayloadChangeReason>

Opens, closes and inspects the popover from anywhere, and connects triggers outside it. Create one with createPopoverController().

Type
PopupController<any, PopoverOpenChangeReason, {}, string, PopoverPayloadChangeReason>
debug?boolean

Logs every state change with its reason to the console, in development builds.

delay?number

Milliseconds the pointer rests on the trigger before the popover opens, with openOnHover.

Default
300
devices?MicSelectorDevice[]

The microphones to list instead of the browser's: your own list, or a demo's. Without it, it lists the browser's.

dismissible?boolean

Whether Escape, an outside press, focus or the window leaving, Android's back gesture and a sheet's swipe can close it. Triggers, Close parts and the controller always can. Pass false while it holds unsaved work, and ask in onDismissAttempt.

Default
true
modal?"trap-focus" | boolean

false: the rest of the page stays usable, and focus leaving the popover closes it. true: also traps focus, locks scroll and makes the rest of the page inert, and an outside press only closes the popover. "trap-focus": traps focus but leaves the page scrollable and clickable.

Type
"trap-focus" | boolean
Default
false, or true while it presents as a sheet
onDismissAttempt?(details: DismissAttemptDetails<Extract<Reason, DismissAttemptReason>>) → void

Runs when dismissible refused a dismissal made on purpose: Escape, an outside press, back or a swipe. Focus or the window leaving is refused without it. Ask "Discard changes?" here.

Type
(details: DismissAttemptDetails<Extract<Reason, DismissAttemptReason>>) → void
Parameters

details – DismissAttemptDetails<Extract<Reason

DismissAttemptReason>>

Returns
void
onOpenChangeComplete?(open: boolean) → void

Runs once the popover has finished opening or closing, after any animation.

Parameters

open – boolean

Returns
void
onPayloadChange?(payload: unknown, details: ChangeDetails<PopoverPayloadChangeReason>) → void

Runs when the payload the content shows changes: a trigger with another payload opens the popover, or takes the open popover over, which fires no onOpenChange, and so does a controller's open({ payload }) on the open popover. details.cancel() keeps the previous payload.

Type
(payload: unknown, details: ChangeDetails<PopoverPayloadChangeReason>) → void
Parameters

payload – unknown

details – ChangeDetails<PopoverPayloadChangeReason>

Returns
void
openOnHover?boolean

Whether resting the pointer on the trigger opens the popover. Pressing the trigger still opens it, so keyboard and touch users can too.

Default
false
presentation?PresentationSetting<"popover">

How the popover presents. "sheet" slides it up from the bottom of the screen, where it can be swiped away, and "auto" does that on small touch screens. Decided each time it opens; the server renders "popover" for "auto".

Type
PresentationSetting<"popover">
Default
"popover"
unknownLabel?string

What a microphone the browser gives no name shows, in the list and the trigger, and what the search matches it by.

Default
"Unknown microphone"

MicSelectorTrigger

PropType
controller?PopupController<any, PopoverOpenChangeReason, {}, string, PopoverPayloadChangeReason>

Connects a trigger outside the popover, like one per table row, to the popover with this controller.

Type
PopupController<any, PopoverOpenChangeReason, {}, string, PopoverPayloadChangeReason>
disabled?boolean

Stops the trigger from opening the popover. A native button can't be focused or pressed, unless focusableWhenDisabled is set.

Default
false
focusableWhenDisabled?boolean

Keeps a disabled trigger in the tab order with aria-disabled instead of the native attribute, so it can host a tooltip that says why. Presses still do nothing.

Default
false
payload?unknown

Data for the content to render when this trigger opens the popover, like the row it belongs to.

shortcut?string

A keyboard shortcut that presses the trigger, like "mod+i". mod is Command on Apple platforms and Control elsewhere. Sets aria-keyshortcuts.

render?ReactElement | ((props: object, state: object) => ReactElement)

Replace the host element or compose it with another component.

Type
ReactElement | ((props: object, state: object) => ReactElement)
className?string

Merged with the part's classes.

MicSelectorContent

data-slot="mic-selector-content"

PropType
align?Align

How the popup lines up with the anchor along that side. start and end follow the reading direction. How the popover lines up with the trigger along that side. PopoverContent's default: center.

Default
"start"
alignOffset?number

Shift along the anchor, in pixels. Shift along the trigger, in pixels.

Default
0
anchor?string | Anchor | null

Positions the popup against this instead of its trigger: an element, a CSS selector, a point like { x, y }, or anything with getBoundingClientRect(). It's read on every check, so it can move. A controller's open({ anchor }) wins for that open.

Type
string | Anchor | null
arrowPadding?number

Space to keep between the arrow and the popup's corners, in pixels.

Default
6
collisionPadding?number

Space to keep from the viewport edges, in pixels.

Default
8
container?DocumentFragment | Element | null

Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.

Type
DocumentFragment | Element | null
finalFocus?PopupFocusTarget

Where focus goes when the popover closes while focus is inside it.

Default
"trigger"
initialFocus?PopoverInitialFocus

Where focus goes when the popover opens. Opening on hover never moves focus, and opening with touch focuses the popover itself so no on-screen keyboard appears, unless this is set to something other than "auto".

Default
"auto"
inline?boolean

Renders the popover where it is in the page instead of above it, inside its parent's layout and stacking, and leaves placing it to your CSS: side, align and the offsets don't apply.

Default
false
keepMounted?boolean

Whether the popover stays in the page, hidden, while closed. Its content keeps its state between opens.

Default
false
side?PopoverSide

The side of the trigger it opens on. It flips when there's no room, unless avoidCollisions is off.

sideOffset?number

Gap between the anchor and the popup, in pixels. Gap between the trigger and the popover, in pixels.

Default
4
title?string

The popover's name, read only by screen readers.

Default
"Microphone"
render?ReactElement | ((props: object, state: object) => ReactElement)

Replace the host element or compose it with another component.

Type
ReactElement | ((props: object, state: object) => ReactElement)
className?string

Merged with the part's classes.

CSS variableType
--anchor-widthstring

The anchor's width.

MicSelectorInput

data-slot="mic-selector-input"

PropType
value?string

The search, to control it from the field (cmdk's API).

onValueChange?(search: string) → void

Runs as the search changes.

Parameters

search – string

Returns
void
render?ReactElement | ((props: object, state: object) => ReactElement)

Replace the host element or compose it with another component.

Type
ReactElement | ((props: object, state: object) => ReactElement)
className?string

Merged with the part's classes.

MicSelectorList

data-slot="mic-selector-list"

PropType
errorLabel?string

What the row that asks for the microphone says once asking failed: access refused, no microphone, or a page that may not use one. Picking it asks again.

Default
"Couldn't access the microphone"
permissionLabel?string

The row that asks for the microphone, shown until the page may use it.

Default
"Allow microphone access"
render?ReactElement | ((props: object, state: object) => ReactElement)

Replace the host element or compose it with another component.

Type
ReactElement | ((props: object, state: object) => ReactElement)
className?string

Merged with the part's classes.

MicSelectorEmpty

data-slot="mic-selector-empty"

PropType
render?ReactElement | ((props: object, state: object) => ReactElement)

Replace the host element or compose it with another component.

Type
ReactElement | ((props: object, state: object) => ReactElement)
className?string

Merged with the part's classes.

MicSelectorItem

data-slot="mic-selector-item"

PropType
valuestring

The microphone's deviceId.

disabled?boolean

Keeps the command from running. Arrow keys and the pointer skip it. Sets data-disabled and aria-disabled.

index?number

The command's position among all visible commands, for virtualized lists that render only some. Sets aria-posinset and aria-setsize.

keywords?string[]

More words the search matches.

Default
[device?.label || unknownLabel]
label?string

The text the search matches, when the content isn't plain text. Not the accessible name: use aria-label for that.

onSelect?(value: string) → unknown

Runs when the item runs, by a press or Enter, with its value: value, or its text without one. A Promise marks it pending until it settles.

Parameters

value – string

Returns
unknown
page?string

The page choosing this command opens, by the value of a CommandPage.

shortcut?string

A keyboard shortcut that runs the command while it's in the page, like "mod+p". Sets aria-keyshortcuts, and a CommandShortcut inside shows it.

render?ReactElement | ((props: object, state: object) => ReactElement)

Replace the host element or compose it with another component.

Type
ReactElement | ((props: object, state: object) => ReactElement)
className?string

Merged with the part's classes.

AttributeType
data-checked?string

MicSelectorLabel

<span> data-slot="mic-selector-label"

PropType
deviceobject

The microphone to name.

Type
{ deviceId: string; label: string }
unknownLabel?string

What it shows when the microphone has no name. Inside a MicSelector, the list and the trigger pass MicSelector's unknownLabel.

Default
"Unknown microphone"
className?string

Merged with the part's classes.

MicSelectorValue

<span> data-slot="mic-selector-value"

PropType
placeholder?string

What it says before a microphone is selected.

Default
"Select microphone..."
className?string

Merged with the part's classes.