Skip to content

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

Components

Free

Voice Selector for Vue UI SDK

A searchable dialog of text-to-speech voices, with a play button and the voice's gender, accent and age on each row. For Vue on UI SDK.

On this page11 sections

Voice Selector is a dialog where people search your text-to-speech voices and pick the one the assistant speaks with. A row can carry a play button for a sample, plus the voice's gender, accent and age, so people narrow the list before they listen.

It's a Command inside a Dialog, and it plays no audio itself. For three or four voices with nothing to search, a Select takes less room.

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

Voice Selector anatomy: content, input, item, preview, name, attributes

Usage

<script setup lang="ts">
import { computed, shallowRef, unref } from "vue"
import { useFilter, useListCollection } from "@/lib/list-collection"
import { ChevronsUpDownIcon } from "lucide-vue-next"
import { Button } from "@/components/ui/button"
import {
  VoiceSelector, VoiceSelectorAccent, VoiceSelectorAttributes,
  VoiceSelectorContent, VoiceSelectorDescription, VoiceSelectorEmpty,
  VoiceSelectorGender, VoiceSelectorGroup, VoiceSelectorInput,
  VoiceSelectorItem, VoiceSelectorList, VoiceSelectorName,
  VoiceSelectorPreview, VoiceSelectorTrigger,
} from "@/components/ui/voice-selector"

// React's state setter argument: the next value, or a function of the last.
type SetStateAction<T> = T | ((value: T) => T)

const voices = [
  {
    accent: "american",
    description: "Warm and professional",
    gender: "female" as const,
    label: "Alloy",
    value: "alloy",
  },
  {
    accent: "british",
    description: "Clear and articulate",
    gender: "male" as const,
    label: "Echo",
    value: "echo",
  },
  {
    accent: "australian",
    description: "Friendly and energetic",
    gender: "female" as const,
    label: "Nova",
    value: "nova",
  },
  {
    accent: "american",
    description: "Deep and authoritative",
    gender: "male" as const,
    label: "Onyx",
    value: "onyx",
  },
];

const voice = shallowRef<string | undefined>(undefined)

const setVoice = (next: SetStateAction<typeof voice.value>) => {
  voice.value = typeof next === "function" ? next(voice.value) : next
}

const playing = shallowRef<string | null>(null)

const setPlaying = (next: SetStateAction<typeof playing.value>) => {
  playing.value = typeof next === "function" ? next(playing.value) : next
}

const selected = computed(() => voices.find((item) => item.value === voice.value))

const filterApi = useFilter({ sensitivity: "base" })

const { collection, filter } = useListCollection<(typeof voices)[number]>(computed(() => ({
  filter: unref(filterApi).contains,
  initialItems: voices,
})))

const handleOpenChange = (open: boolean) => {
  if (!open) {
    filter("");
  }
}

const handleInputValueChange = (inputValue: string) => {
  filter(inputValue);
}

const handlePlay = (value: string) => {
  setPlaying(playing.value === value ? null : value);
}
</script>

<template>
  <div class="w-full max-w-xs">
    <VoiceSelector @open-change="handleOpenChange" @value-change="setVoice" :value="voice">
      <VoiceSelectorTrigger>
        <template #render="{ props }">
          <Button v-bind="props" class="w-full justify-between" variant="outline">
            {{ selected ? selected.label : "Select a voice..." }}<ChevronsUpDownIcon aria-hidden="true" class="text-muted-foreground" />
          </Button>
        </template>
      </VoiceSelectorTrigger>
      <VoiceSelectorContent
        :collection="collection"
        @input-value-change="handleInputValueChange"
      >
        <VoiceSelectorInput placeholder="Search voices..." />
        <VoiceSelectorList>
          <VoiceSelectorEmpty>No voices found.</VoiceSelectorEmpty>
          <VoiceSelectorGroup heading="Available voices">
            <VoiceSelectorItem v-for="item in collection.items" :item="item" :key="item.value">
              <VoiceSelectorPreview
                :label="item.label"
                @play="() => handlePlay(item.value)"
                :playing="playing === item.value"
              />
              <div class="flex min-w-0 flex-1 flex-col">
                <VoiceSelectorName>{{ item.label }}</VoiceSelectorName>
                <VoiceSelectorDescription>
                  {{ item.description }}
                </VoiceSelectorDescription>
              </div>
              <VoiceSelectorAttributes class="gap-2">
                <VoiceSelectorGender :value="item.gender" />
                <VoiceSelectorAccent :value="item.accent" />
              </VoiceSelectorAttributes>
            </VoiceSelectorItem>
          </VoiceSelectorGroup>
        </VoiceSelectorList>
      </VoiceSelectorContent>
    </VoiceSelector>
  </div>
</template>

Accessibility

The trigger opens a modal dialog with focus in the search field, which takes its name from its placeholder. The dialog's title is read only by screen readers, Voice Selector unless you set title on VoiceSelectorContent. Focus stays in the field while the arrow keys move a highlight through the voices. The list is a listbox, and the picked voice reports aria-current. Gender and accent are read as words. A play button reads Play preview until you pass the voice's name as its label, which makes it Play Alloy. It sits inside its row, so its label is read as part of the voice's name, and Tab reaches it.

Arrow Down
Highlights the next voice, and stays on the last one.
Arrow Up
Highlights the previous voice, and stays on the first one.
Command+Arrow Down
Highlights the last voice. Cmd + ArrowDown on a Mac.
Command+Arrow Up
Highlights the first voice. Cmd + ArrowUp on a Mac.
Page Down
Moves the highlight ten voices down.
Page Up
Moves the highlight ten voices up.
Ctrl+N
On a Mac, highlights the next voice, as ArrowDown does.
Ctrl+P
On a Mac, highlights the previous voice, as ArrowUp does.
Enter
In the search field, picks the highlighted voice and closes the dialog. On a play button, plays or pauses its sample without picking the voice.
Space
On a play button, plays or pauses its sample without picking the voice.
Tab
Moves focus from the search field to the play buttons, one row at a time.
Escape
Clears the search field. When it's already empty, closes the dialog without a change.

Demos

Attributes

Six voices from OpenAI and ElevenLabs in two groups, with Sage picked at the start. Under each name, VoiceSelectorAttributes lines up a gender symbol, an accent flag, an age and one word on the tone, split by VoiceSelectorBullet. The search matches the voice's name only. Use it when people narrow a long list by trait before they listen.

Preview width

Preview

Onyx, Alloy and Nova each have a VoiceSelectorPreview, labelled with the voice's name, that speaks a line through the browser's speech synthesis at that voice's pitch and rate. The button spins until speech starts, shows pause while it plays and never picks the voice, and closing the dialog stops the sample. Swap the synthesis for an <audio> element and a sample file per voice to play a provider's real voices.

Preview width

Shortcuts

Four voices with VoiceSelectorShortcut hints from ⌥1 to ⌥4, and a key listener that picks a voice with Alt and its number while the dialog is open. The hint is only text, so the listener is yours to write, and the picked voice keeps its check beside the hint. Use shortcuts for a few voices people switch between often.

Preview width

Controlled

An Assistant voice settings row holds open and value in its own state. Its Change button sits outside VoiceSelector and opens the dialog by setting open, and the line under the label shows the picked voice. Control open when the dialog opens from a menu item, a first-run screen or anything else that isn't a trigger.

Preview width

AI SDK

The picked value is the voice the speech model speaks with. Send it with the text to a route that calls generateSpeech, and play the audio that comes back.

import { openai } from "@ai-sdk/openai";
import { generateSpeech } from "ai";

export async function POST(request: Request) {
  const { text, voice } = await request.json();
  const { audio } = await generateSpeech({
    model: openai.speech("gpt-4o-mini-tts"),
    text,
    voice,
  });

  return new Response(audio.uint8Array, {
    headers: { "Content-Type": audio.mediaType },
  });
}

The same route can make each voice's preview. Call it once per voice with a short line and keep the files, rather than paying for a new sample on every press.

Migrating from AI SDK Elements

AI SDK Elements is for React. In Vue, Voice Selector has the same parts and props, and the demos above show them in Vue's syntax.

FAQ

How does the Voice Selector play button play a voice sample?

It doesn't play anything. VoiceSelectorPreview fires @play when pressed, and your code plays the sample, binding :loading while it loads and :playing while it plays, which swap the icon for a spinner or a pause sign. Presses while it loads are ignored.

Give each button the voice's name as label, so screen readers hear Play Alloy rather than the same Play preview on every row. The Preview demo speaks through the browser's speech synthesis. For a provider's real voices, play a stored sample file per voice in an <audio> element, and stop it when the open state turns false, as the demo does.

How do I get the voice someone picks in Voice Selector?

Listen for @value-change, which receives the picked voice's value as a string, and the dialog closes. Bind :value from your state to control it, or set default-value to start from one voice, and the picked row shows a check.

Store the value, not the label, and send it to your speech model as the voice, as the AI SDK section does.

Which genders and accents can Voice Selector show?

VoiceSelectorGender draws a symbol for six values, male, female, transgender, androgyne, non-binary and intersex, and a small circle when you leave value out. Any other string, such as a provider's own Male, shows the small circle too, and screen readers still hear the word, so map your data to those six when you want the symbols.

VoiceSelectorAccent shows a flag for 35 accents, from american to vietnamese, and an accent it doesn't know as its name in text. Both read the word to screen readers, and children you pass replace the drawing and that word together.

Why do the Voice Selector accent flags show as letters on Windows?

The flags are emoji, and Windows' emoji font has no country flags, so the British flag shows as the two letters GB. macOS, iOS and Android draw the flag itself.

To show flags everywhere, pass your own children to VoiceSelectorAccent, such as a small SVG flag. Children replace the default content, the hidden accent name included, so put the name back as text that screen readers can read.

How do I open Voice Selector from my own button?

Hold open in a ref, bind it with :open, set it to true from your button and update it from @open-change, as the Controlled demo does. The dialog still closes on Escape, a click outside or a pick, reports that through @open-change, and returns focus to the element that had it before.

Can Voice Selector be used with the keyboard?

Yes. The trigger opens the dialog with focus in the search field, typing filters the list, the arrow keys move through the voices, and Enter picks one and closes the dialog. Tab moves on to the play buttons, where Enter or Space plays a sample without picking the voice, and Escape first clears the search, then closes the dialog.

The Accessibility section lists every key.

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

It has the same parts and props as AI SDK Elements' React version, with a description beside the title, accent names read aloud and a check on the picked voice. AI SDK Elements has no Vue version, so there is nothing to migrate, and the demos above are the place to start.

API Reference

VoiceSelector

PropType
open?boolean

Whether the dialog is open, when controlled. Two-way with v-model:open.

defaultOpen?boolean

Whether the dialog starts open, when uncontrolled.

Default
false
value?string

The picked voice's value, when controlled. Two-way with v-model.

defaultValue?string

The voice picked at first, when uncontrolled.

closeOnOutsidePress?boolean

Whether pressing outside the dialog, like on its backdrop, closes it. The press counts once it's released outside too, so dragging a text selection out of a field doesn't close it.

Default
true, or false when `modal` is false
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, DialogOpenChangeReason, {}, any, DialogPayloadChangeReason>

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

Type
PopupController<any, DialogOpenChangeReason, {}, any, DialogPayloadChangeReason>
debug?boolean

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

dismissible?boolean

Whether Escape, an outside press and Android's back gesture can close the dialog. Close parts, triggers and the controller always can. Pass false while a form has unsaved changes, and ask in onDismissAttempt.

Default
true
modal?"trap-focus" | boolean

true: the rest of the page is inert and doesn't scroll, focus is trapped, and an outside press only closes the dialog. "trap-focus": traps focus, and leaves the page scrollable and clickable. false: a dialog beside the page, which Tab can leave and outside presses don't close.

Type
"trap-focus" | boolean
Default
true
pendingAnnouncement?string

What screen readers hear once a Close part's action has been running for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.

Default
"Loading"
persistentElements?(string | Element)[] | (() → Element[])

Elements that stay usable while the dialog makes the page inert, like a chat launcher or a password manager's button. Elements, CSS selectors, or a function that returns elements, read when the dialog opens. Presses on them never close it.

Type
(string | Element)[] | (() → Element[])
Parameters

string | Element)[] | ((

Returns
Element[])
presentation?PresentationSetting<"dialog">

How the dialog 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 "dialog" for "auto".

Type
PresentationSetting<"dialog">
Default
"dialog"
EventType
@open-change(open: boolean) → void

Called when the dialog opens or closes.

Parameters

open – boolean

Returns
void
@value-change(value: string) → void

Called with a voice's value when one is picked.

Parameters

value – string

Returns
void
@dismiss-attempt(details: DialogDismissAttemptDetails) → void

Runs when a dismissal was refused, because dismissible is false, an outside press doesn't close it, or a Close part's action is running. Ask "Discard changes?" here.

Type
(details: DialogDismissAttemptDetails) → void
Parameters

details – DialogDismissAttemptDetails

Returns
void
@open-change-complete(open: boolean) → void

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

Parameters

open – boolean

Returns
void
@payload-change(payload: unknown, details: ChangeDetails<DialogPayloadChangeReason>) → void

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

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

payload – unknown

details – ChangeDetails<DialogPayloadChangeReason>

Returns
void

VoiceSelectorTrigger

data-slot="voice-selector-trigger"

PropType
controller?PopupController<any, DialogOpenChangeReason, {}, any, DialogPayloadChangeReason>

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

Type
PopupController<any, DialogOpenChangeReason, {}, any, DialogPayloadChangeReason>
disabled?boolean

Stops the trigger from opening the dialog. 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 dialog, like the row it belongs to.

shortcut?string

A keyboard shortcut that presses the trigger, like "mod+k". mod is Command on Apple platforms and Control elsewhere. Sets aria-keyshortcuts, and a Shortcut part inside shows it. A modal dialog pauses the page's shortcuts while it's open.

#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

VoiceSelectorContent

data-slot="voice-selector-content"

PropType
bottomStickOnMobile?boolean

Stick the dialog to the bottom of the screen on mobile. DialogContent's default: true.

Default
false
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
description?string

The dialog's description, for screen readers.

Default
"Search for a voice and pick one."
finalFocus?PopupFocusTarget

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

Default
"trigger"
initialFocus?DialogInitialFocus

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

Default
"auto"
inline?boolean

Renders the dialog and its backdrop where they are in the page instead of above it, so it can stay inside a frame, like an app preview. Pair it with modal="trap-focus" to keep the rest of the page usable. A container on the dialog still moves its backdrop, so leave it off.

Default
false
keepMounted?boolean

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

Default
false
showCloseButton?boolean

Show close button at the top right corner. DialogContent's default: true.

Default
false
size?"2xl" | "3xl" | "4xl" | "5xl" | "6xl" | "fullscreen" | "lg" | "md" | "sm" | "xl"

DialogContent's default: md.

Type
"2xl" | "3xl" | "4xl" | "5xl" | "6xl" | "fullscreen" | "lg" | "md" | "sm" | "xl"
Default
lg
title?string

The dialog's title, for screen readers.

Default
"Voice Selector"
#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

VoiceSelectorInput

data-slot="voice-selector-input"

PropType
value?string

The search, to control it from the field (cmdk's API). Two-way with v-model.

#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

EventType
@value-change(search: string) → void

Runs as the search changes.

Parameters

search – string

Returns
void

VoiceSelectorList

data-slot="voice-selector-list"

PropType
#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

VoiceSelectorEmpty

data-slot="voice-selector-empty"

PropType
#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

VoiceSelectorGroup

data-slot="voice-selector-group"

PropType
heading?VNode

The group's heading, which names it.

#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

VoiceSelectorItem

data-slot="voice-selector-item"

PropType
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.

label?string

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

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.

value?string

Passed to onAction and onValueChange, and identifies the command. Without it, one is generated.

#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

EventType
@select(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
AttributeType
data-checked?string

Mirrors checked.

VoiceSelectorShortcut

data-slot="voice-selector-shortcut"

PropType
shortcut?string

The keys to show, like "mod+p". Inside a command, its shortcut.

#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

VoiceSelectorSeparator

data-slot="voice-selector-separator"

PropType
#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

VoiceSelectorGender

<span> data-slot="voice-selector-gender"

PropType
value?VoiceSelectorGenderValue

The voice's gender, drawn as its symbol and read out as its name.

class?string

Merged with the part's classes.

VoiceSelectorAccent

<span> data-slot="voice-selector-accent"

PropType
value?string

The accent, such as british: shown as its country's flag.

class?string

Merged with the part's classes.

VoiceSelectorAge

<span> data-slot="voice-selector-age"

PropType
class?string

Merged with the part's classes.

VoiceSelectorName

<span> data-slot="voice-selector-name"

PropType
class?string

Merged with the part's classes.

VoiceSelectorDescription

<span> data-slot="voice-selector-description"

PropType
class?string

Merged with the part's classes.

VoiceSelectorAttributes

<div> data-slot="voice-selector-attributes"

PropType
class?string

Merged with the part's classes.

VoiceSelectorBullet

<span> data-slot="voice-selector-bullet"

PropType
class?string

Merged with the part's classes.

VoiceSelectorPreview

data-slot="voice-selector-preview"

PropType
clickEffect?boolean

Apply a click effect to the button.

Default
true
debug?boolean

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

disabled?boolean

Stops presses. The button is natively disabled, so it leaves the tab order and its form doesn't submit through it, unless focusableWhenDisabled is set.

Default
false
focusableWhenDisabled?boolean

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

Default
false
isLoading?boolean

Show a loading indicator.

Default
false
label?string

The voice's name, which the button's label ends with: Play Alloy, Pause Alloy.

Default
"preview"
loading?boolean

Shows a spinner while the sample loads. The button keeps focus and ignores presses until it's done.

pendingAnnouncement?string

What screen readers hear once the button has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.

Default
"Loading"
pill?boolean

Fully rounded corners.

Default
false
playing?boolean

Shows pause instead of play while the sample plays.

size?"default" | "icon" | "icon-lg" | "icon-md" | "icon-sm" | "icon-xl" | "icon-xs" | "lg" | "md" | "sm" | "xl" | "xs"

The size.

Type
"default" | "icon" | "icon-lg" | "icon-md" | "icon-sm" | "icon-xl" | "icon-xs" | "lg" | "md" | "sm" | "xl" | "xs"
Default
"md"
type?"button" | "reset" | "submit"

What a native button does in a form: "submit" submits it and "reset" resets it. Ignored when the button renders as something else.

Type
"button" | "reset" | "submit"
Default
"button"
variant?"default" | "destructive" | "ghost" | "link" | "outline" | "secondary"

The visual style.

Type
"default" | "destructive" | "ghost" | "link" | "outline" | "secondary"
Default
"default"
#render?{ props, state, children }

A slot that renders your own element: bind its props with v-bind="props". It also gets the part's state, and children, its content.

class?string

Merged with the part's classes.

EventType
@click( event: MouseEvent, details?: ButtonActionDetails ) → unknown

Runs when the button is pressed. Return a Promise to keep it pending (data-pending) until it settles. details.source says how it was pressed; a wrapper passing the click on may leave it out.

Type
( event: MouseEvent, details?: ButtonActionDetails ) → unknown
Parameters

event – React.MouseEvent<HTMLButtonElement>

details? – ButtonActionDetails

Returns
unknown
@play() → void

Called on press. Play or pause the sample here.

Returns
void

useVoiceSelector