# Voice input

> Dictate a prompt: a waveform from your real mic level, a timer, then transcribing.

Speaking is faster than typing, if you can tell the app is listening. It’s one surface from start to finish: the mic button stretches into the listening bar as the mic blurs into Stop. Your voice runs through the bar as a trace of hairlines on a baseline with a faint reflection under it, drawn from your microphone’s level, so it reacts to you rather than looping: new sound arrives in ink at the far end and greys as it travels back, like a tape of the last few seconds; the timer’s seconds roll, and words appear above as they’re recognised. Stop settles the trace flat into its baseline as "Transcribing" rises over it, then the bar shrinks back into the mic. If the browser blocks the mic, the icon crosses out and how to fix it opens beside it instead of failing silently.

## Install

```bash
npx shadcn@latest add https://hairlineui.com/r/voice-input.json
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `number-roll`, `text-morph`
- Docs and live preview: https://hairlineui.com/ui/voice-input
- Registry item (source): https://hairlineui.com/r/voice-input.json

## Usage

```tsx
import { VoiceInput } from "@/components/voice-input";

<VoiceInput status={status} level={level} startedAt={startedAt} onStart={start} onStop={stop} onCancel={cancel} />
```

## With the AI SDK

```tsx
// app/api/transcribe/route.ts
import { experimental_transcribe as transcribe } from "ai";
import { openai } from "@ai-sdk/openai";

export async function POST(req: Request) {
  const audio = new Uint8Array(await req.arrayBuffer());
  const { text } = await transcribe({ model: openai.transcription("whisper-1"), audio });
  return Response.json({ text });
}

// The client: record, measure the level, send the audio
"use client";
import { useRef, useState } from "react";
import { VoiceInput, type VoiceStatus } from "@/components/voice-input";

export function Dictate({ onText }: { onText: (text: string) => void }) {
  const [status, setStatus] = useState<VoiceStatus>("idle");
  const [level, setLevel] = useState(0);
  const [startedAt, setStartedAt] = useState<number>();
  const finish = useRef<(send: boolean) => void>(undefined);

  async function start() {
    let stream: MediaStream;
    try {
      stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    } catch {
      return setStatus("blocked");
    }
    const audio = new AudioContext();
    const analyser = audio.createAnalyser();
    audio.createMediaStreamSource(stream).connect(analyser);
    const samples = new Uint8Array(analyser.fftSize);
    const meter = setInterval(() => {
      analyser.getByteTimeDomainData(samples);
      setLevel(Math.max(...samples.map((v) => Math.abs(v - 128))) / 128);
    }, 80);

    const chunks: Blob[] = [];
    const recorder = new MediaRecorder(stream);
    recorder.ondataavailable = (e) => chunks.push(e.data);
    recorder.start();
    setStartedAt(Date.now());
    setStatus("listening");

    finish.current = (send) => {
      clearInterval(meter);
      recorder.onstop = async () => {
        stream.getTracks().forEach((track) => track.stop());
        audio.close();
        if (!send) return setStatus("idle");
        setStatus("transcribing");
        try {
          const res = await fetch("/api/transcribe", { method: "POST", body: new Blob(chunks) });
          if (!res.ok) throw new Error(res.statusText);
          onText((await res.json()).text);
          setStatus("idle");
        } catch {
          setStatus("error");
        }
      };
      recorder.stop();
    };
  }

  return (
    <VoiceInput
      status={status}
      level={level}
      startedAt={startedAt}
      onStart={start}
      onStop={() => finish.current?.(true)}
      onCancel={() => finish.current?.(false)}
    />
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `status` | `"idle" \| "listening" \| "transcribing" \| "blocked" \| "error"` | – | Where dictation is. |
| `level` | `number` | – | Current mic level, 0 to 1, read every frame; without it the trace runs on a gentle stand-in of syllables and pauses. |
| `transcript` | `string` | – | Words recognised so far, e.g. from the Web Speech API. |
| `startedAt` | `number` | – | When listening started (ms); shows the timer. |
| `onStart / onStop / onCancel` | `() => void` | – | Mic button and Try again; Stop and transcribe; Cancel. |
| `errorText` | `string` | – | Overrides the blocked or error explanation. |
| `align` | `"start" \| "end"` | `"start"` | Which side the mic sits on; the bar grows from there. Use "end" for a mic beside Send. |

## States

- **idle**: A mic button labelled "Dictate".
- **listening**: The button stretches into a 44px bar over 520ms while the mic blurs into Stop; the trace (one hairline per 1/24 s, flowing in from the far end and greying as it travels), a timer whose seconds roll and Cancel fade in once there’s room. The transcript so far opens above.
- **transcribing**: Stop blurs into a spinner, the trace settles flat into its baseline (about 0.4s) and fades as "Transcribing" rises under a sweep of light; afterwards the bar shrinks back into the mic.
- **blocked**: Microphone permission was denied: the mic blurs into a crossed-out one and where to allow it opens beside it, with Try again.
- **error**: Nothing usable was heard; the title morphs to "Didn’t catch that", with Try again.

## What it handles

Speaking is faster than typing, if you can tell the app is listening. This shows that it is, reacts to the voice, and explains what to do when the microphone is blocked.

- **One surface from start to finish**: The mic button stretches into the listening bar as the mic blurs into Stop, and shrinks back afterwards.
- **A waveform from the real mic level**: Pass the level and the hairline trace reacts to the voice instead of looping; new sound is ink and greys as it ages.
- **Words as they are recognised**: The transcript so far opens above the bar, and the timer’s seconds roll.
- **A transcribing state**: Stop becomes a spinner, the trace settles flat into its baseline and “Transcribing” rises over it.
- **Blocked microphones are explained**: The icon crosses out, where to allow it opens beside it, and Try again is offered.
- **Fits beside Send**: Set align="end" and the bar grows leftwards from a mic that sits next to the Send button.

## Replaces

a mic button, a waveform, a recording timer, a transcribing state, a permission-denied message

## Where it fits

- **AI chat composers**: Dictate a prompt instead of typing it.
- **Notes and journaling apps**: Speak a note and have it transcribed.
- **Support and CRM tools**: Dictate a reply or a call summary.
- **Forms with long answers**: A mic for fields where typing is a chore.

## Notes

- Buttons are labelled "Dictate", "Stop and transcribe" and "Cancel"; listening and transcribing are announced as status.
- The waveform is decorative (aria-hidden); the timer and transcript carry the information.
- Blocked and error use role="alert". Give the component the width the bar should fill; the mic stretches across it from its own side: align="start" (default) grows rightwards, align="end" puts the mic beside Send and grows leftwards, mirroring the bar and the error line.
- Installs Number roll and Text morph. With reduced motion the bar changes size in place and the trace holds still. The trace is two SVG paths written from one frame loop that runs only while listening or settling.

License: MIT (https://hairlineui.com/license#components)
