← Components

Communication

Voice input

A mic button with a soft blob that wobbles with your voice level. Never starts on its own; shows a clear Listening state.

Examples and variants

Simulated level

Press the mic (this demo fakes the level, no microphone).

Example
function VoiceDemo() {
  const [listening, setListening] = useState(false)
  const [level, setLevel] = useState(0)
  useEffect(() => {
    if (!listening) return
    const timer = window.setInterval(() => setLevel(Math.random()), tokenMs("--duration-quick") * 0.8)
    return () => window.clearInterval(timer)
  }, [listening])
  return <VoiceInput listening={listening} onListeningChange={setListening} level={listening ? level : 0} />
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/voice-input.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install cn lucide-react
  2. Copy this file to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/voice-input.tsxvoice-input
      components/ui/voice-input.tsx
      "use client"
      
      import * as React from "react"
      import { MicIcon, MicOffIcon } from "lucide-react"
      import { cn } from "cn"
      
      /*
        Voice input: a mic button that shows your voice level while listening.
        The ring is a soft blob that wobbles with the level (smoothed, about 8
        updates a second). It never starts on its own. Pass `level` (0 to 1) to
        drive it from your own audio pipeline; otherwise it reads the microphone.
      */
      function VoiceInput({
        listening,
        onListeningChange,
        level: levelProp,
        label = "Voice input",
        className,
      }: {
        listening: boolean
        onListeningChange: (listening: boolean) => void
        /** 0 to 1. When given, the mic isn't opened. */
        level?: number
        label?: string
        className?: string
      }) {
        const [micLevel, setMicLevel] = React.useState(0)
        const [denied, setDenied] = React.useState(false)
        const level = levelProp ?? micLevel
      
        React.useEffect(() => {
          if (!listening || levelProp !== undefined) return
          let stream: MediaStream | null = null
          let context: AudioContext | null = null
          let timer = 0
          let cancelled = false
          navigator.mediaDevices
            ?.getUserMedia({ audio: true })
            .then((s) => {
              if (cancelled) return s.getTracks().forEach((t) => t.stop())
              stream = s
              context = new AudioContext()
              const analyser = context.createAnalyser()
              analyser.fftSize = 256
              context.createMediaStreamSource(s).connect(analyser)
              const data = new Uint8Array(analyser.frequencyBinCount)
              let smooth = 0
              timer = window.setInterval(() => {
                analyser.getByteFrequencyData(data)
                const avg = data.reduce((sum, v) => sum + v, 0) / data.length / 255
                smooth = smooth * 0.6 + avg * 0.4
                setMicLevel(Math.min(1, smooth * 2.5))
              }, 125)
            })
            .catch(() => {
              setDenied(true)
              onListeningChange(false)
            })
          return () => {
            cancelled = true
            window.clearInterval(timer)
            stream?.getTracks().forEach((t) => t.stop())
            void context?.close()
          }
        }, [listening, levelProp, onListeningChange])
      
        return (
          <span data-slot="voice-input" className={cn("inline-flex items-center gap-2", className)}>
            <span className="relative inline-flex">
              {listening ? (
                <span
                  aria-hidden
                  className="voice-ring voice-blob pointer-events-none absolute inset-0 rounded-full bg-(--voice-ring)"
                  style={{ scale: String(1 + level * 0.6), opacity: 0.18 + level * 0.3 }}
                />
              ) : null}
              <button
                type="button"
                aria-pressed={listening}
                aria-label={listening ? `${label}: stop listening` : `${label}: start listening`}
                onClick={() => onListeningChange(!listening)}
                className={cn(
                  "liquid-press relative inline-flex size-(--voice-size) items-center justify-center rounded-full outline-none focus-visible:shadow-(--focus-ring) [&_svg]:size-(--size-icon-md)",
                  listening ? "bg-(--voice-ring) text-(--color-fg-on-accent)" : "bg-(--voice-container) text-foreground hover:bg-(--voice-container-hover) active:bg-(--voice-container-pressed)"
                )}
              >
                {denied ? <MicOffIcon /> : <MicIcon />}
              </button>
            </span>
            <span role="status" className={cn("text-sm", listening ? "text-foreground" : "sr-only")}>
              {denied ? "Microphone blocked" : listening ? "Listening" : ""}
            </span>
          </span>
        )
      }
      
      export { VoiceInput }
      

Imports

What the examples on this page import:

Imports
import { Attachment } from "@/components/ui/attachment"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Bubble, BubbleGroup, BubbleReactions } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import { CodeBlock } from "@/components/ui/code-block"
import { Marker } from "@/components/ui/marker"
import { Message, MessageAvatar, MessageContent, MessageFooter, MessageHeader } from "@/components/ui/message"
import { MessageScroller } from "@/components/ui/message-scroller"
import { PromptInput } from "@/components/ui/prompt-input"
import { Questionnaire } from "@/components/ui/questionnaire"
import { StreamingText } from "@/components/ui/streaming-text"
import { Trace, TraceItem } from "@/components/ui/trace"
import { VoiceInput } from "@/components/ui/voice-input"
import { tokenMs } from "@/lib/motion/token-ms"

Anatomy

  1. 1Button · --voice-size.
  2. 2Blob · --voice-ring; scale follows the level.
  3. 3Status · Listening / Microphone blocked.

Props

PropTypeDefaultDescription
listening, onListeningChangeboolean handlers—Controlled state.
levelnumber—0 to 1. Without it, the mic is read (after permission).

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

TokenPoints toLightDark
--voice-ringvar(--color-info)oklch(0.6 0.17 248)oklch(0.72 0.14 245)
--voice-containervar(--surface-container)oklch(0.965 0.005 95)oklch(0.12 0 0)
--voice-container-hovercolor-mix(in oklch, var(--voice-container), var(--on-surface) var(--state-hover-mix))color-mix(in oklch, var(--voice-container), var(--on-surface) var(--state-hover-mix))same
--voice-container-pressedcolor-mix(in oklch, var(--voice-container), var(--on-surface) var(--state-pressed-mix))color-mix(in oklch, var(--voice-container), var(--on-surface) var(--state-pressed-mix))same
--voice-sizevar(--size-control-md)40pxsame

Motion

TriggerWhat happensTokens
ListeningThe blob scales with the level and wobbles.--duration-fast, --duration-pulse

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • aria-pressed; status text says Listening.
  • Never auto-starts.

Usage

Do

  • Offer voice next to the text field.

Don’t

  • Don't start listening without a press.

Code

components/ui/voice-input.tsx
"use client"

import * as React from "react"
import { MicIcon, MicOffIcon } from "lucide-react"
import { cn } from "cn"

/*
  Voice input: a mic button that shows your voice level while listening.
  The ring is a soft blob that wobbles with the level (smoothed, about 8
  updates a second). It never starts on its own. Pass `level` (0 to 1) to
  drive it from your own audio pipeline; otherwise it reads the microphone.
*/
function VoiceInput({
  listening,
  onListeningChange,
  level: levelProp,
  label = "Voice input",
  className,
}: {
  listening: boolean
  onListeningChange: (listening: boolean) => void
  /** 0 to 1. When given, the mic isn't opened. */
  level?: number
  label?: string
  className?: string
}) {
  const [micLevel, setMicLevel] = React.useState(0)
  const [denied, setDenied] = React.useState(false)
  const level = levelProp ?? micLevel

  React.useEffect(() => {
    if (!listening || levelProp !== undefined) return
    let stream: MediaStream | null = null
    let context: AudioContext | null = null
    let timer = 0
    let cancelled = false
    navigator.mediaDevices
      ?.getUserMedia({ audio: true })
      .then((s) => {
        if (cancelled) return s.getTracks().forEach((t) => t.stop())
        stream = s
        context = new AudioContext()
        const analyser = context.createAnalyser()
        analyser.fftSize = 256
        context.createMediaStreamSource(s).connect(analyser)
        const data = new Uint8Array(analyser.frequencyBinCount)
        let smooth = 0
        timer = window.setInterval(() => {
          analyser.getByteFrequencyData(data)
          const avg = data.reduce((sum, v) => sum + v, 0) / data.length / 255
          smooth = smooth * 0.6 + avg * 0.4
          setMicLevel(Math.min(1, smooth * 2.5))
        }, 125)
      })
      .catch(() => {
        setDenied(true)
        onListeningChange(false)
      })
    return () => {
      cancelled = true
      window.clearInterval(timer)
      stream?.getTracks().forEach((t) => t.stop())
      void context?.close()
    }
  }, [listening, levelProp, onListeningChange])

  return (
    <span data-slot="voice-input" className={cn("inline-flex items-center gap-2", className)}>
      <span className="relative inline-flex">
        {listening ? (
          <span
            aria-hidden
            className="voice-ring voice-blob pointer-events-none absolute inset-0 rounded-full bg-(--voice-ring)"
            style={{ scale: String(1 + level * 0.6), opacity: 0.18 + level * 0.3 }}
          />
        ) : null}
        <button
          type="button"
          aria-pressed={listening}
          aria-label={listening ? `${label}: stop listening` : `${label}: start listening`}
          onClick={() => onListeningChange(!listening)}
          className={cn(
            "liquid-press relative inline-flex size-(--voice-size) items-center justify-center rounded-full outline-none focus-visible:shadow-(--focus-ring) [&_svg]:size-(--size-icon-md)",
            listening ? "bg-(--voice-ring) text-(--color-fg-on-accent)" : "bg-(--voice-container) text-foreground hover:bg-(--voice-container-hover) active:bg-(--voice-container-pressed)"
          )}
        >
          {denied ? <MicOffIcon /> : <MicIcon />}
        </button>
      </span>
      <span role="status" className={cn("text-sm", listening ? "text-foreground" : "sr-only")}>
        {denied ? "Microphone blocked" : listening ? "Listening" : ""}
      </span>
    </span>
  )
}

export { VoiceInput }