AI Voice

Voice input for agents: a waveform dictation panel with a live transcript, a face you talk with, and a push-to-talk composer row.

Installation

Installation

One command adds ai-voice and the shared AI Kit layer it is built on (tokens, faces, marks and brand icons). No animation library, light and dark built in.

$npx shadcn@latest add https://tweenui.dev/r/ai-voice.json
ai-voice-demo
components/ui/ai-voice-demo.tsx
"use client"

import * as React from "react"

import { AiDemo } from "@/lib/ai-demo"
import { paceToken, typeInto, useAiLoop } from "@/lib/ai-kit"
import { AiPushToTalk, AiVoiceOrb, AiWaveform } from "@/registry/tween/ai-voice"

const frame: React.CSSProperties = {
  display: "grid",
  justifyItems: "center",
  width: "100%",
}
const clock = (seconds: number) =>
  `0:${String(Math.floor(seconds)).padStart(2, "0")}`

/** A believable voice envelope: a slow swell, a fast flutter and a little noise. */
const speak = (count: number, tick: number, gain = 1) =>
  Array.from({ length: count }, (_, at) => {
    const swell = 0.5 + 0.5 * Math.sin(tick * 0.55 + at * 0.42)
    const flutter = 0.5 + 0.5 * Math.sin(tick * 1.7 + at * 1.9)
    const noise = 0.7 + Math.random() * 0.3
    return gain * (0.12 + 0.88 * swell * (0.35 + 0.65 * flutter) * noise)
  })
const hush = (count: number) => Array.from({ length: count }, () => 0.08)
const frozen = (count: number) =>
  Array.from(
    { length: count },
    (_, at) => 0.2 + 0.7 * Math.abs(Math.sin(at * 0.9))
  )

const SAID =
  "Make the cards fan out when the section scrolls in, and slow the last one down."

function Waveform() {
  const root = React.useRef<HTMLDivElement>(null)
  const [status, setStatus] = React.useState<"idle" | "recording" | "done">(
    "recording"
  )
  const [levels, setLevels] = React.useState(() => frozen(28))
  const [seconds, setSeconds] = React.useState(3)
  const [said, setSaid] = React.useState(
    "Make the cards fan out when the section scrolls in"
  )
  const [hands, setHands] = React.useState(false)

  useAiLoop(
    root,
    async ({ sleep }) => {
      setStatus("recording")
      setSaid("")
      setSeconds(0)
      setLevels(hush(28))
      await sleep(500)
      let live = true
      const meter = (async () => {
        for (let tick = 0; live; tick++) {
          setLevels(speak(28, tick))
          setSeconds(tick / 9)
          await sleep(110)
        }
      })()
      const text = (async () => {
        await sleep(400)
        let line = ""
        for (const word of SAID.split(" ")) {
          line = line ? `${line} ${word}` : word
          setSaid(line)
          await sleep(paceToken(word, 150))
        }
        await sleep(500)
        live = false
      })()
      try {
        await Promise.all([meter, text])
      } finally {
        live = false
      }
      setLevels(hush(28))
      setStatus("done")
      await sleep(2200)
    },
    { gap: 300, enabled: !hands }
  )

  // Once the visitor takes over, the mic button runs a live meter by hand.
  React.useEffect(() => {
    if (!hands || status !== "recording") return
    let tick = 0
    const timer = window.setInterval(() => {
      tick += 1
      setLevels(speak(28, tick))
      setSeconds(tick / 9)
    }, 110)
    return () => window.clearInterval(timer)
  }, [hands, status])

  return (
    <div ref={root} style={frame} onPointerDown={() => setHands(true)}>
      <AiWaveform
        levels={levels}
        status={status}
        time={clock(seconds)}
        transcript={said}
        onToggle={() => {
          if (status === "recording") {
            setStatus("done")
            setLevels(hush(28))
          } else {
            setStatus("recording")
            setSaid("")
          }
        }}
      />
    </div>
  )
}

const ASKED = "How do I slow down the card ring reveal?"
const ANSWER =
  "Pass a longer duration, like 1.5 seconds. The stagger scales with it."
type OrbStatus = "idle" | "listening" | "thinking" | "speaking"

function Orb() {
  const root = React.useRef<HTMLDivElement>(null)
  const [status, setStatus] = React.useState<OrbStatus>("listening")
  const [level, setLevel] = React.useState(0.5)
  const [heard, setHeard] = React.useState(ASKED)
  const [reply, setReply] = React.useState("")
  const [hands, setHands] = React.useState(false)

  useAiLoop(
    root,
    async ({ sleep }) => {
      setStatus("listening")
      setHeard("")
      setReply("")
      setLevel(0)
      await sleep(500)
      let live = true
      const pulse = (async () => {
        for (let tick = 0; live; tick++) {
          setLevel(
            (0.5 + 0.5 * Math.sin(tick * 0.9)) * (0.5 + Math.random() * 0.5)
          )
          await sleep(130)
        }
      })()
      const text = (async () => {
        await typeInto(setHeard, ASKED, sleep, 46)
        await sleep(500)
        live = false
      })()
      try {
        await Promise.all([pulse, text])
      } finally {
        live = false
      }
      setLevel(0)
      setStatus("thinking")
      await sleep(1100)
      setStatus("speaking")
      let line = ""
      for (const word of ANSWER.split(" ")) {
        line = line ? `${line} ${word}` : word
        setReply(line)
        await sleep(paceToken(word, 120))
      }
      await sleep(500)
      setStatus("idle")
      await sleep(1800)
    },
    { gap: 300, enabled: !hands, still: () => setLevel(0.5) }
  )

  React.useEffect(() => {
    if (!hands || status !== "listening") return
    let tick = 0
    const timer = window.setInterval(() => {
      tick += 1
      setLevel((0.5 + 0.5 * Math.sin(tick * 0.9)) * (0.5 + Math.random() * 0.5))
    }, 130)
    return () => window.clearInterval(timer)
  }, [hands, status])

  return (
    <div ref={root} style={frame} onPointerDown={() => setHands(true)}>
      <AiVoiceOrb
        status={status}
        level={level}
        heard={heard}
        reply={reply}
        label={status === "speaking" ? "Mira is speaking" : undefined}
        onToggle={() => {
          if (status === "listening") {
            setStatus("idle")
          } else {
            setStatus("listening")
            setHeard("Listening to you now")
            setReply("")
          }
        }}
      />
    </div>
  )
}

const HEARD = "Swap the hero image for the dark one"
type TalkStatus = "idle" | "recording" | "transcribing" | "ready"

function PushToTalk() {
  const root = React.useRef<HTMLDivElement>(null)
  const [status, setStatus] = React.useState<TalkStatus>("idle")
  const [levels, setLevels] = React.useState(() => hush(44))
  const [seconds, setSeconds] = React.useState(0)
  const [text, setText] = React.useState("")
  const [hands, setHands] = React.useState(false)

  useAiLoop(
    root,
    async ({ sleep }) => {
      setStatus("idle")
      setText("")
      setLevels(hush(44))
      await sleep(1500)
      setStatus("recording")
      for (let tick = 0; tick < 30; tick++) {
        setLevels(speak(44, tick, 0.95))
        setSeconds(tick / 9)
        await sleep(110)
      }
      setLevels(hush(44))
      setStatus("transcribing")
      await sleep(900)
      setStatus("ready")
      await typeInto(setText, HEARD, sleep, 16)
      await sleep(1900)
    },
    {
      gap: 200,
      enabled: !hands,
      still: () => {
        setStatus("recording")
        setSeconds(2)
        setLevels(frozen(44))
      },
    }
  )

  React.useEffect(() => {
    if (!hands) return
    if (status === "recording") {
      let tick = 0
      const timer = window.setInterval(() => {
        tick += 1
        setLevels(speak(44, tick, 0.95))
        setSeconds(tick / 9)
      }, 110)
      return () => window.clearInterval(timer)
    }
    if (status === "transcribing") {
      const timer = window.setTimeout(() => {
        setText(HEARD)
        setStatus("ready")
      }, 900)
      return () => window.clearTimeout(timer)
    }
  }, [hands, status])

  return (
    <div
      ref={root}
      style={frame}
      onPointerDown={() => setHands(true)}
      onKeyDown={() => setHands(true)}
    >
      <AiPushToTalk
        status={status}
        levels={levels}
        time={clock(seconds)}
        transcript={text}
        onTranscriptChange={setText}
        onStart={() => {
          setSeconds(0)
          setStatus("recording")
        }}
        onStop={() => setStatus("transcribing")}
        onCancel={() => setStatus("idle")}
        onSend={() => {
          setText("")
          setStatus("idle")
        }}
      />
    </div>
  )
}

export function AiVoiceDemo({ only }: { only?: string }) {
  return (
    <AiDemo
      only={only}
      tabs={[
        { name: "Waveform", node: <Waveform /> },
        { name: "Orb", node: <Orb /> },
        { name: "Push to talk", node: <PushToTalk /> },
      ]}
    />
  )
}

Installation

pnpm dlx shadcn@latest add https://tweenui.dev/r/ai-voice.json

Usage

import { AiPushToTalk, AiVoiceOrb, AiWaveform } from "@/components/ui/ai-voice"
<AiWaveform
  levels={levels}
  status={recording ? "recording" : "done"}
  time="0:03"
  transcript={transcript}
  onToggle={() => setRecording(!recording)}
/>

These components draw the voice UI and report gestures. They do not open the microphone. Feed levels from your own analyser (one number from 0 to 1 per bar) and transcript from your speech-to-text.

Versions

  • AiWaveform is a dictation panel. Bars scale with levels and the transcript streams in underneath, each new word fading in. When recording stops the bars settle and the mic turns green.
  • AiVoiceOrb is a conversation with a face. Two halos follow level while it listens, then pulse outward while it speaks and the reply streams.
  • AiPushToTalk is a composer row. Hold the mic or Space and it becomes a recorder with a clock and a level strip. Release and it shows the sentence in an editable field, with send where the mic was. Escape cancels.

Props

AiWaveform

PropTypeDefaultDescription
levelsnumber[]One level per bar, 0 to 1.
status"idle" | "recording" | "done""recording"Colours the mic and the bars.
labelstringThe line beside the mic.
timestringElapsed time, already formatted.
transcriptstring""What has been heard so far.
placeholderstringShown while the transcript is empty.
onToggle() => voidMakes the mic a button.

AiVoiceOrb

PropTypeDefaultDescription
status"idle" | "listening" | "thinking" | "speaking""listening"Drives the face, the halos and the caption.
levelnumber0Voice level from 0 to 1 while listening.
heardstring""What the person said.
replystring""What the agent says back.
labelstringOverrides the caption.
tone, shapeface look"teal", "orb"The face and the halo colour.
onToggle() => voidMakes the face a button.

AiPushToTalk

PropTypeDefaultDescription
status"idle" | "recording" | "transcribing" | "ready""idle"Which pane the row shows.
levelsnumber[][]Level strip while recording.
timestring"0:00"Elapsed recording time.
transcriptstring""The recognised sentence.
onTranscriptChange(value: string) => voidMakes the transcript editable.
onStart, onStop() => voidThe mic or Space going down and coming up.
onCancel() => voidEscape or the cancel button while recording.
onSend(value: string) => voidEnter or the send button once ready.
notestringOverrides the hint under the row.