# AI voice input

> Minimal floating voice capture control with circular record toggle, tabular timer, 48-tick waveform rail and playback review controls.

- Kind: block · Category: AI · Interactivity: script
- Install: `npx shadcn@latest add @haze/ai-voice`
- File: `src/components/haze/blocks/ai-voice.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/ai-voice

## Use when
- Capturing short spoken prompts or voice memos inside an AI assistant card
- Letting users review, play back, discard or send a recorded clip before transcription
- Demonstrating a calm voice input workflow that degrades cleanly under reduced motion

## Avoid when
- Users primarily type long structured prompts with files and slash commands; use ai-prompt instead

## Alternatives
- [ai-prompt](https://hazeui.com/blocks/ai-prompt.md)
- [ai-composer](https://hazeui.com/blocks/ai-composer.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-voice" | no | Unique prefix for the section heading reference. |
| heading | `string` | "AI voice input" | no | Heading displayed at the top of the voice capture card. |
| sampleTranscript | `string` | "Remind the platform team to rotate staging webhook keys before Friday's deploy window." | no | Demo transcript rendered in the sent voice note chip. |
| maxDurationSeconds | `number` | 60 | no | Maximum recording duration in seconds before auto-stopping to review. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- The microphone button updates aria-label and aria-pressed as capture moves from idle to recording to review.
- Waveform animation stops under prefers-reduced-motion while preserving static bar levels, timer updates and polite role="status" announcements.
- Key Space / Enter: Start or stop recording, toggle playback review, discard or send the voice note
- Key Tab: Move between the record button, review toolbar actions and sent transcript dismiss button

## Agent prompts

### Install and use

Install the Haze UI block "AI voice input" with `npx shadcn@latest add @haze/ai-voice`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AiVoice from "@/components/haze/blocks/ai-voice.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/blocks/ai-voice.md

### Customize with real content

Adapt the Haze ai-voice block for our product. Replace the demo values of these props with our real content: id, heading, sampleTranscript, maxDurationSeconds, class. Keep the layout, the heading level rules and these accessibility details: The microphone button updates aria-label and aria-pressed as capture moves from idle to recording to review. Waveform animation stops under prefers-reduced-motion while preserving static bar levels, timer updates and polite role="status" announcements. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-voice, check it fits: use it when capturing short spoken prompts or voice memos inside an ai assistant card; letting users review, play back, discard or send a recorded clip before transcription; demonstrating a calm voice input workflow that degrades cleanly under reduced motion. Avoid it when users primarily type long structured prompts with files and slash commands; use ai-prompt instead. Alternatives: @haze/ai-prompt, @haze/ai-composer.

## Example requests that should lead here
- Add an AI voice input card with a record button, tabular timer, 24-bar waveform and play, discard, send review controls
- Create a centered voice memo recorder that displays a simulated transcript chip when sent

## Source

```astro
---
import { Mic, Pause, Play, Send, Square, Trash, Volume2, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  id?: string;
  heading?: string;
  sampleTranscript?: string;
  maxDurationSeconds?: number;
  class?: string;
}

const {
  id = "haze-ai-voice",
  heading = "AI voice input",
  sampleTranscript = "Remind the platform team to rotate staging webhook keys before Friday's deploy window.",
  maxDurationSeconds = 60,
  class: className,
} = Astro.props;

const barCount = 48;
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-voice
  data-transcript={sampleTranscript}
  data-max-seconds={String(maxDurationSeconds)}
  class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
  <h2 id={`${id}-title`} class="sr-only">{heading}</h2>

  <div class="mx-auto flex max-w-md flex-col items-center py-6">
    <div class="relative flex items-center justify-center">
      <span
        data-av-pulse
        hidden
        aria-hidden="true"
        class="pointer-events-none absolute inset-0 animate-ping rounded-full border border-frame-strong bg-muted/40"
      ></span>
      <button
        type="button"
        data-av-record
        aria-label="Start recording"
        aria-pressed="false"
        class="relative z-10 inline-flex size-16 cursor-pointer items-center justify-center rounded-full border border-frame bg-field text-foreground transition-[background-color,border-color,color,scale] duration-150 ease-snappy hover:border-frame-strong hover:bg-accent/50 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95"
      >
        <span data-av-icon-mic>
          <Mic class="size-6" aria-hidden="true" />
        </span>
        <span data-av-icon-stop hidden>
          <Square class="size-5 fill-current" aria-hidden="true" />
        </span>
      </button>
    </div>

    <p
      data-av-timer
      class="mt-4 font-mono text-sm/5 text-muted-foreground tabular-nums"
    >
      00:00
    </p>

    <div
      data-av-wave
      aria-hidden="true"
      class="mt-5 flex h-8 w-full max-w-72 items-center justify-between"
    >
      {
        Array.from({ length: barCount }).map(() => (
          <span
            data-av-bar
            style="height: 12%"
            class="w-0.5 shrink-0 rounded-full bg-muted-foreground/35 transition-[height,background-color] duration-150 ease-snappy"
          />
        ))
      }
    </div>

    <p data-av-state-label class="mt-5 text-xs/5 text-muted-foreground">
      Click to speak
    </p>

    <div
      data-av-review
      hidden
      class="mt-5 flex flex-wrap items-center justify-center gap-2"
    >
      <button
        type="button"
        data-av-play
        class="inline-flex min-h-8 cursor-pointer items-center gap-1.5 rounded-full border border-frame bg-field px-3.5 text-xs font-medium text-foreground transition-colors duration-150 ease-snappy hover:border-frame-strong hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75"
      >
        <span data-av-play-icon>
          <Play class="size-3.5" aria-hidden="true" />
        </span>
        <span data-av-pause-icon hidden>
          <Pause class="size-3.5" aria-hidden="true" />
        </span>
        <span data-av-play-label>Play</span>
      </button>

      <button
        type="button"
        data-av-discard
        class="inline-flex min-h-8 cursor-pointer items-center gap-1.5 rounded-full border border-frame bg-field px-3.5 text-xs font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:border-destructive-border hover:bg-destructive/10 hover:text-destructive focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75"
      >
        <Trash class="size-3.5" aria-hidden="true" />
        <span>Discard</span>
      </button>

      <button
        type="button"
        data-av-send
        class="inline-flex min-h-8 cursor-pointer items-center gap-1.5 rounded-full bg-primary px-4 text-xs font-medium text-primary-foreground transition-[opacity,scale] duration-150 ease-snappy hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75"
      >
        <Send class="size-3.5" aria-hidden="true" />
        <span>Send</span>
      </button>
    </div>

    <div
      data-av-sent
      hidden
      class="mt-5 flex w-full items-start justify-between gap-3 rounded-2xl border border-border bg-card p-3.5 shadow-key"
    >
      <div class="flex min-w-0 items-start gap-2.5">
        <span class="grid size-7 shrink-0 place-items-center rounded-full border border-frame bg-muted/50 text-foreground" aria-hidden="true">
          <Volume2 class="size-3.5" />
        </span>
        <div class="min-w-0">
          <div class="flex flex-wrap items-center gap-2">
            <span class="text-xs/4 font-medium text-foreground">Voice note sent</span>
            <span
              data-av-sent-duration
              class="font-mono text-xs text-muted-foreground tabular-nums"
            >
              00:00
            </span>
          </div>
          <p data-av-sent-text class="mt-1 wrap-anywhere text-xs/5 text-muted-foreground"></p>
        </div>
      </div>

      <button
        type="button"
        data-av-dismiss-sent
        aria-label="Dismiss voice transcript"
        class="inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
      >
        <X class="size-3.5" aria-hidden="true" />
      </button>
    </div>

    <p data-av-status role="status" class="sr-only"></p>
  </div>
</section>

<script>
  type VoiceMode = "idle" | "recording" | "review";

  function initAiVoiceInputs() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-voice]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const recordBtn = root.querySelector<HTMLButtonElement>("[data-av-record]");
      const iconMic = root.querySelector<HTMLElement>("[data-av-icon-mic]");
      const iconStop = root.querySelector<HTMLElement>("[data-av-icon-stop]");
      const pulseRing = root.querySelector<HTMLElement>("[data-av-pulse]");
      const stateLabel = root.querySelector<HTMLElement>("[data-av-state-label]");
      const timerEl = root.querySelector<HTMLElement>("[data-av-timer]");
      const bars = Array.from(root.querySelectorAll<HTMLElement>("[data-av-bar]"));
      const reviewBar = root.querySelector<HTMLElement>("[data-av-review]");
      const playBtn = root.querySelector<HTMLButtonElement>("[data-av-play]");
      const playIcon = root.querySelector<HTMLElement>("[data-av-play-icon]");
      const pauseIcon = root.querySelector<HTMLElement>("[data-av-pause-icon]");
      const playLabel = root.querySelector<HTMLElement>("[data-av-play-label]");
      const discardBtn = root.querySelector<HTMLButtonElement>("[data-av-discard]");
      const sendBtn = root.querySelector<HTMLButtonElement>("[data-av-send]");
      const sentBox = root.querySelector<HTMLElement>("[data-av-sent]");
      const sentDuration = root.querySelector<HTMLElement>("[data-av-sent-duration]");
      const sentText = root.querySelector<HTMLElement>("[data-av-sent-text]");
      const dismissSentBtn = root.querySelector<HTMLButtonElement>("[data-av-dismiss-sent]");
      const status = root.querySelector<HTMLElement>("[data-av-status]");

      const transcript = root.dataset.transcript ?? "Voice note transcribed and ready.";
      const maxSeconds = Math.max(5, Number(root.dataset.maxSeconds ?? "60") || 60);
      const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
      const count = bars.length || 48;

      const idleHeights = Array.from({ length: count }, () => 12);
      const staticActiveHeights = Array.from({ length: count }, (_, i) => {
        const env = Math.sin((i / Math.max(1, count - 1)) * Math.PI);
        const ripple = Math.abs(Math.sin(i * 0.72) * 0.6 + Math.cos(i * 1.35) * 0.4);
        return Math.max(16, Math.min(96, Math.round(18 + env * 72 * ripple)));
      });

      let mode: VoiceMode = "idle";
      let elapsedSeconds = 0;
      let recordedSeconds = 0;
      let capturedHeights = [...staticActiveHeights];
      let liveLevels = [...idleHeights];
      let isPlaying = false;
      let playCursor = 0;
      let clockTimer: number | undefined;
      let waveTimer: number | undefined;
      let playTimer: number | undefined;
      let sampleStep = 0;

      const formatTime = (sec: number) => {
        const mins = Math.floor(sec / 60);
        const rem = sec % 60;
        return `${String(mins).padStart(2, "0")}:${String(rem).padStart(2, "0")}`;
      };

      const announce = (msg: string) => {
        if (status) status.textContent = msg;
      };

      const clearTimers = () => {
        if (clockTimer !== undefined) {
          window.clearInterval(clockTimer);
          clockTimer = undefined;
        }
        if (waveTimer !== undefined) {
          window.clearInterval(waveTimer);
          waveTimer = undefined;
        }
        if (playTimer !== undefined) {
          window.clearInterval(playTimer);
          playTimer = undefined;
        }
      };

      const paintBars = (heights: number[], activePredicate: (idx: number, height: number) => boolean) => {
        bars.forEach((bar, idx) => {
          const h = heights[idx] ?? 12;
          bar.style.height = `${h}%`;
          const active = activePredicate(idx, h);
          bar.classList.toggle("bg-foreground", active);
          bar.classList.toggle("bg-muted-foreground/35", !active);
        });
      };

      const syncPlayButton = () => {
        if (playIcon) playIcon.hidden = isPlaying;
        if (pauseIcon) pauseIcon.hidden = !isPlaying;
        if (playLabel) playLabel.textContent = isPlaying ? "Pause" : "Play";
      };

      const stopPlayback = () => {
        if (playTimer !== undefined) {
          window.clearInterval(playTimer);
          playTimer = undefined;
        }
        isPlaying = false;
        syncPlayButton();
      };

      const enterIdle = (message?: string) => {
        clearTimers();
        mode = "idle";
        elapsedSeconds = 0;
        recordedSeconds = 0;
        isPlaying = false;
        playCursor = 0;
        liveLevels = [...idleHeights];

        if (stateLabel) stateLabel.textContent = "Click to speak";
        if (timerEl) timerEl.textContent = "00:00";
        if (reviewBar) reviewBar.hidden = true;
        if (iconMic) iconMic.hidden = false;
        if (iconStop) iconStop.hidden = true;
        if (pulseRing) pulseRing.hidden = true;
        if (recordBtn) {
          recordBtn.setAttribute("aria-label", "Start recording");
          recordBtn.setAttribute("aria-pressed", "false");
          recordBtn.classList.remove("border-primary", "bg-primary", "text-primary-foreground");
          recordBtn.classList.add("border-frame", "bg-field", "text-foreground");
        }
        syncPlayButton();
        paintBars(idleHeights, () => false);
        if (message) announce(message);
      };

      const enterReview = () => {
        clearTimers();
        mode = "review";
        recordedSeconds = Math.max(1, elapsedSeconds);
        capturedHeights = reducedMotion ? [...staticActiveHeights] : [...liveLevels];
        isPlaying = false;
        playCursor = 0;

        if (stateLabel) stateLabel.textContent = "Review recording";
        if (timerEl) timerEl.textContent = formatTime(recordedSeconds);
        if (reviewBar) reviewBar.hidden = false;
        if (iconMic) iconMic.hidden = false;
        if (iconStop) iconStop.hidden = true;
        if (pulseRing) pulseRing.hidden = true;
        if (recordBtn) {
          recordBtn.setAttribute("aria-label", "Record again");
          recordBtn.setAttribute("aria-pressed", "false");
          recordBtn.classList.remove("border-primary", "bg-primary", "text-primary-foreground");
          recordBtn.classList.add("border-frame", "bg-field", "text-foreground");
        }
        syncPlayButton();
        paintBars(capturedHeights, () => false);
        announce(`Recording captured (${formatTime(recordedSeconds)}). Ready to review.`);
      };

      const startRecording = () => {
        clearTimers();
        mode = "recording";
        elapsedSeconds = 0;
        isPlaying = false;
        playCursor = 0;
        liveLevels = [...staticActiveHeights];

        if (stateLabel) stateLabel.textContent = "Listening…";
        if (timerEl) timerEl.textContent = "00:00";
        if (reviewBar) reviewBar.hidden = true;
        if (iconMic) iconMic.hidden = true;
        if (iconStop) iconStop.hidden = false;
        if (pulseRing) pulseRing.hidden = reducedMotion;
        if (recordBtn) {
          recordBtn.setAttribute("aria-label", "Stop recording");
          recordBtn.setAttribute("aria-pressed", "true");
          recordBtn.classList.remove("border-frame", "bg-field", "text-foreground");
          recordBtn.classList.add("border-primary", "bg-primary", "text-primary-foreground");
        }

        paintBars(liveLevels, (_, h) => reducedMotion || h >= 36);
        announce("Listening. Click stop to review recording.");

        clockTimer = window.setInterval(() => {
          elapsedSeconds++;
          if (timerEl) timerEl.textContent = formatTime(elapsedSeconds);
          if (elapsedSeconds >= maxSeconds) {
            enterReview();
          }
        }, 1000);

        if (!reducedMotion) {
          waveTimer = window.setInterval(() => {
            sampleStep++;
            const waveA = Math.sin(sampleStep * 0.55) * 30;
            const waveB = Math.cos(sampleStep * 1.18) * 20;
            const nextLevel = Math.max(16, Math.min(96, Math.round(50 + waveA + waveB)));
            liveLevels.shift();
            liveLevels.push(nextLevel);
            paintBars(liveLevels, (_, h) => h >= 36);
          }, 100);
        }
      };

      recordBtn?.addEventListener("click", () => {
        if (mode === "recording") {
          enterReview();
        } else {
          startRecording();
        }
      });

      playBtn?.addEventListener("click", () => {
        if (mode !== "review") return;
        if (isPlaying) {
          stopPlayback();
          announce("Playback paused.");
          return;
        }
        if (playCursor >= bars.length) {
          playCursor = 0;
        }
        isPlaying = true;
        syncPlayButton();
        announce("Playing recording preview.");

        if (reducedMotion) {
          playCursor = bars.length;
          paintBars(capturedHeights, () => true);
          if (timerEl) timerEl.textContent = formatTime(recordedSeconds);
          stopPlayback();
          announce("Playback finished.");
          return;
        }

        const stepMs = Math.max(55, Math.round((Math.min(recordedSeconds, 5) * 1000) / bars.length));
        playTimer = window.setInterval(() => {
          playCursor++;
          paintBars(capturedHeights, (idx) => idx < playCursor);
          const progressSec = Math.min(
            recordedSeconds,
            Math.round((playCursor / bars.length) * recordedSeconds)
          );
          if (timerEl) timerEl.textContent = `${formatTime(progressSec)} / ${formatTime(recordedSeconds)}`;
          if (playCursor >= bars.length) {
            stopPlayback();
            if (timerEl) timerEl.textContent = formatTime(recordedSeconds);
            announce("Playback finished.");
          }
        }, stepMs);
      });

      discardBtn?.addEventListener("click", () => {
        enterIdle("Recording discarded.");
      });

      sendBtn?.addEventListener("click", () => {
        const durLabel = formatTime(Math.max(1, recordedSeconds));
        if (sentBox) sentBox.hidden = false;
        if (sentDuration) sentDuration.textContent = durLabel;
        if (sentText) sentText.textContent = transcript;
        enterIdle(`Voice note sent (${durLabel}): "${transcript}"`);
      });

      dismissSentBtn?.addEventListener("click", () => {
        if (sentBox) sentBox.hidden = true;
        announce("Dismissed voice transcript.");
      });
    });
  }

  initAiVoiceInputs();
  document.addEventListener("astro:page-load", initAiVoiceInputs);
</script>
```
