# Speech Input

> React speech to text button on the Web Speech API: live interim text, a mic ring that follows your voice, Escape to stop, no API key and no dependencies.

- Kind: Component (AI chat)
- Docs: https://ui.minidev.pro/docs/speech-input
- Source (registry JSON with the full file): https://ui.minidev.pro/r/speech-input.json
- License: MIT. One file, yours to edit after install.

## When to use

Put it in the toolbar of PromptInput or AiComposer. Click to start, click again or press Escape to stop. `onTranscript(text, { final })` fires with grey-preview text (`final: false`) while you speak and with settled text (`final: true`) when a phrase ends: append final text, replace the preview. It needs `SpeechRecognition`, which Chrome, Edge and Safari have and Firefox does not; there the button is disabled with a tooltip that says so. It calls no service of its own and needs no API key. To record an audio file instead of text use AudioRecorder.

## Installation

### shadcn CLI (copies the source into your project)

```bash
npx shadcn@latest add @minidev/speech-input
```

Writes `components/ui/speech-input.tsx` plus the MiniDev files it is built from (icon-button, kbd, tooltip) and installs its npm dependencies. Older CLI versions: `npx shadcn@latest add https://ui.minidev.pro/r/speech-input.json`.

### npm package

```bash
npm i minidev-ui-kit lucide-react motion
```

Add the tokens to your global stylesheet once:

```css
@import "tailwindcss";
@import "minidev-ui-kit/styles.css";
@source "../node_modules/minidev-ui-kit";
```

Next.js also needs `transpilePackages: ["minidev-ui-kit"]` in next.config.

## Import

After the shadcn install:

```tsx
import { SpeechInput } from "@/components/ui/speech-input"
```

From the npm package:

```tsx
import { SpeechInput } from "minidev-ui-kit/ui/speech-input"
```

## Usage

```tsx
import { SpeechInput } from "@/components/ui/speech-input"

export function Example() {
  return (
    <SpeechInput />
  )
}
```

## Props

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| `onTranscript` | `(text: string, meta: { final: boolean }) => void` | - | no | Fires with recognised text. `final: false` is a live guess that will be replaced; `final: true` is settled. |
| `lang` | `string` | - | no | BCP 47 language to recognise, e.g. "en-GB" or "hi-IN". Defaults to the browser language (`navigator.language`). |
| `continuous` | `boolean` | `true` | no | Keep listening across pauses until stopped. When false, it stops after the first phrase. |
| `interim` | `boolean` | `true` | no | Send interim guesses (`final: false`) while the user speaks. |
| `onError` | `(error: string) => void` | - | no | Fires with the Web Speech error code: "not-allowed", "audio-capture", "network", "no-speech"... |
| `onUnsupported` | `() => void` | - | no | Fires once after mount when the browser has no speech recognition. |
| `disabled` | `boolean` | - | no | Disables the button and stops listening if it is on. |
| `size` | `"sm" \| "md"` | `"md"` | no | 32px (sm) or 36px (md). |
| `aria-label` | `string` | - | no | Accessible name of the button, also its tooltip. Defaults to "Dictate". |
| `className` | `string` | - | no |  |

## Examples

### Dictate into a prompt

Settled text is appended to the prompt; the live guess shows in grey under it until the phrase ends.

```tsx
function DictatedPrompt() {
  const [prompt, setPrompt] = React.useState("")
  const [preview, setPreview] = React.useState("")
  return (
    <div className="flex w-full max-w-lg flex-col gap-2">
      <PromptInput
        value={prompt}
        onChange={setPrompt}
        onSubmit={() => setPrompt("")}
        placeholder="Ask about your invoices, or dictate"
        toolbar={
          <SpeechInput
            size="sm"
            onTranscript={(text, { final }) => {
              if (final) {
                setPrompt((p) => `${p} ${text.trim()}`.trim())
                setPreview("")
              } else setPreview(text)
            }}
          />
        }
      />
      <p aria-hidden className="min-h-5 px-4 text-[0.8125rem] text-fg-subtle italic">{preview}</p>
    </div>
  )
}
```

### Notes with a set language

lang picks the recognition language. The preview sits inline after the settled text, in a lighter colour.

```tsx
function MeetingNote() {
  const [text, setText] = React.useState("")
  const [preview, setPreview] = React.useState("")
  return (
    <div className="w-full max-w-md rounded-xl border border-border bg-surface p-4 shadow-raised">
      <div className="flex items-center justify-between gap-3">
        <p className="text-[0.8125rem] font-medium text-fg">Call notes: Northwind renewal</p>
        <SpeechInput
          lang="en-GB"
          aria-label="Dictate call notes"
          onTranscript={(chunk, { final }) => {
            if (final) {
              setText((t) => `${t} ${chunk.trim()}`.trim())
              setPreview("")
            } else setPreview(chunk)
          }}
        />
      </div>
      <p className="mt-3 min-h-16 text-sm leading-6 text-fg">
        {text} <span className="text-fg-subtle">{preview}</span>
      </p>
    </div>
  )
}
```

### Sizes and states

sm is 32px for composer toolbars, md is 36px. In Firefox the button is disabled and its tooltip says why.

```tsx
<SpeechInput size="sm" />
<SpeechInput />
<SpeechInput disabled />
```

## Keyboard interactions

| Key | Action |
| --- | --- |
| `Enter` or `Space` | On the button, starts listening, or stops when it is already listening. |
| `Escape` | Stops listening wherever focus is, for example while typing in the prompt. The listener is only attached while listening. |

## Accessibility

- The button keeps one name, `aria-label` ("Dictate" by default), and exposes the listening state as `aria-pressed`. The icon swaps from a microphone to a stop square.
- Without speech recognition the button uses `focusableWhenDisabled`: it stays in the Tab order with `aria-disabled="true"`, and `aria-describedby` points to hidden text that says voice input is not supported.
- Errors appear as inline text with `role="alert"`, so screen readers read them as they appear.
- The level ring is `aria-hidden`. Under reduced motion it stays at a fixed size and the level stream is never opened.

## FAQ

### Which browsers support SpeechInput?

Browsers with `SpeechRecognition` or `webkitSpeechRecognition`: Chrome, Edge and Safari. Firefox has neither, so the button is disabled, its tooltip says "Voice input is not supported in this browser" and `onUnsupported` fires once. The component calls no service and needs no key, but Chrome recognises speech on a server, so it fails offline with the `network` error.

### How do I show the words in grey while the user is still speaking?

`onTranscript` fires with `final: false` for a live guess that the next call replaces, and `final: true` when a phrase settles. Keep the guess in its own state: `if (final) { setPrompt((p) => (p + " " + text).trim()); setPreview("") } else setPreview(text)`. Set `interim={false}` to get settled text only.

### What happens when the user blocks the microphone?

The browser reports `not-allowed`, and SpeechInput shows "Microphone access is blocked. Allow it in the browser's site settings." next to the button and calls `onError("not-allowed")`. The message clears on the next start. `audio-capture` (no microphone) and `no-speech` get their own messages.

### Does SpeechInput record or upload audio?

No, it only returns text. While listening it opens a second microphone stream with `getUserMedia` to read the level for the ring through an `AnalyserNode`, records nothing and stops it when listening ends. To save an audio file use [`AudioRecorder`](https://ui.minidev.pro/docs/audio-recorder).

## Rules for generating code

- Use semantic tokens only (bg, surface, sunken, border, fg, fg-muted, fg-subtle, ink, accent, success, warning, danger). Never raw hex or palette steps like blue-500.
- Shadows only from the set: shadow-xs, shadow-sm, shadow-raised, shadow-md, shadow-lg, shadow-overlay.
- Numbers use tabular-nums. Dark mode is the `dark` class on <html>; components never branch on theme.

## Dependencies

- npm: `lucide-react`, `motion`
- Built from: [icon-button](https://ui.minidev.pro/docs/icon-button/md), [kbd](https://ui.minidev.pro/docs/kbd/md), [tooltip](https://ui.minidev.pro/docs/tooltip/md)

## Related

- [Prompt Input](https://ui.minidev.pro/docs/prompt-input/md): An AI chat composer that grows with its content, sends on Enter, adds a newline on Shift Enter and has attach, toolbar and send controls. Built for React.
- [Ai Composer](https://ui.minidev.pro/docs/ai-composer/md): Chat input for AI apps with a multiline textarea, Enter to send, suggestion chips, attach button, model picker and a stop button while a response streams.
- [Audio Recorder](https://ui.minidev.pro/docs/audio-recorder/md): React audio recorder on MediaRecorder with start, pause and stop, an elapsed timer, live waveform bars, playback with a scrubber, download and a max length.
- [Agent Trace](https://ui.minidev.pro/docs/agent-trace/md): React timeline of an AI agent run: each tool step shows pending, running, done or error, reports its duration and folds out details. The header sums up the run.
- [Artifact Preview](https://ui.minidev.pro/docs/artifact-preview/md): Framed preview for AI generated artifacts such as code, documents or UI, with a title bar, copy button and optional expand action for a full view.
- [Attachment Chip](https://ui.minidev.pro/docs/attachment-chip/md): Compact Tailwind file chip with a paperclip icon, truncated filename and an optional remove button, for attachments in chat composers, emails and forms.

---

All 557 components: https://ui.minidev.pro/llms.txt (full text: https://ui.minidev.pro/llms-full.txt).
