Setting up Voice Preview
Voice Preview is a voice-first assistant widget: a breathing orb, four RunAsh personas, live speech recognition, and Claude replies streamed back sentence-by-sentence through the browser’s own text-to-speech engine. This guide walks through installing it, wiring it to /api/chat, and understanding every moving part.
Try the phases
Waiting. Tap the orb or press Space to start.
Overview
What the component does before you wire anything up.
The widget renders a single animated orb that reflects five states — idle, listening, processing, speaking, and error — and drives two independent browser capabilities: the SpeechRecognition API for capturing what someone says, and speechSynthesis for reading Claude’s reply back out loud. In between, it streams the model’s response through your own /api/chat proxy and speaks each sentence as soon as it finishes arriving, rather than waiting for the full reply.
A text-input fallback is built in for browsers without speech recognition (Safari, most of them), and a “Use Claude API” toggle lets you demo the whole flow offline with canned persona replies before you spend a single token.
Nothing here needs new dependencies. It’s a self-contained client component built on browser APIs and your existing Anthropic proxy — no new npm packages, no new backend service.
Prerequisites
Confirm these before you drop the component in.
| "use client" boundary | The whole component is browser-API-driven (mic, speech synthesis, canvas) and must run client-side. |
| /api/chat route already exists | Voice Preview calls it directly for streamed replies — it doesn't talk to Anthropic itself. |
| ANTHROPIC_API_KEY set server-side | Needed only once you flip "Use Claude API" on in Settings; the canned-reply fallback works without it. |
| HTTPS or localhost | Browsers only grant microphone access on secure origins. |
| Chromium-based browser for testing mic input | Speech recognition support is inconsistent elsewhere. |
Guided setup
Seven steps from file to first working reply. Check them off as you go — your progress is saved in this browser.
Rendering the component
Speech APIs don’t exist during server-side rendering, so load it with ssr: false:
import dynamic from "next/dynamic"
const VoicePreview = dynamic(
() => import("@/components/studio/voice-preview"),
{ ssr: false }
)
export default function StudioPage() {
return <VoicePreview />
}The /api/chat contract it expects
If your proxy route already follows the RunAsh convention, this works unchanged:
import Anthropic from "@anthropic-ai/sdk"
import { NextRequest } from "next/server"
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY })
export async function POST(req: NextRequest) {
const { messages, system, model = "claude-sonnet-4-20250514", stream = true } = await req.json()
if (stream) {
const encoder = new TextEncoder()
const readable = new ReadableStream({
async start(controller) {
const response = await client.messages.stream({ model, max_tokens: 1024, system, messages })
for await (const chunk of response) {
if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ text: chunk.delta.text })}\n\n`))
}
}
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
controller.close()
},
})
return new Response(readable, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
}
const response = await client.messages.create({ model, max_tokens: 1024, system, messages })
return Response.json(response)
}Voice Preview passes 1024 as max_tokens (matching the RunAsh chat default) and its own persona systemPrompt per turn.
Architecture
The state machine and pipeline underneath the orb.
Phase state machine
Every visual state in the component reduces to one of five phases, held in a single phase state variable:
An error phase can interrupt from anywhere — a denied microphone, an unsupported browser, or a recognition failure all land there, with a “Try again” control to reset back to idle.
Listening → amplitude
On startListening, the component requests a microphone stream with getUserMedia, feeds it into a Web Audio AnalyserNode, and samples frequency data every animation frame to drive the orb’s breathing radius and the 28-bar waveform. Recognition itself runs in parallel through SpeechRecognition, with interimResults on so partial transcripts appear as italic text under the orb while you’re still talking.
Processing → streaming → speaking
Once a final transcript lands, runTurn sends the full message history to /api/chat. As text deltas stream back, a small sentence extractor (extractSentences) watches the growing buffer for anything ending in . ! ? and pushes each complete sentence onto a TTS queue immediately — so speech starts on the first sentence Claude finishes, not after the whole reply arrives. A SpeechSynthesisUtterance plays each queued sentence in order, chained through its own onend handler.
Continuous mode
With Continuous mode on, the mic automatically reopens 300ms after the assistant finishes speaking — turning single exchanges into a hands-free back-and-forth conversation.
Personas
Four presets, each pairing a system prompt with a distinct voice and orb color.
Direct, strategic, energetic — built for live-selling flow and CTA timing questions, capped at short answers.
Calm and precise, for thorough, well-structured answers with a measured, thoughtful tone.
Vivid and punchy — the pick for ad copy, hooks, and stream scripts that need to land fast.
Senior-engineer tone: precise, prefers code examples, keeps explanations concise.
Adding a fifth persona
Every persona is one object in the PERSONAS array — name, tagline, a voice-name fragment to match against speechSynthesis.getVoices(), a speed/pitch pair, a system prompt, and three orb gradient stops plus a glow color. Add an entry there and it appears in the picker automatically; no other file needs to change.
Settings reference
Everything a viewer can change, and where it's remembered.
All settings persist to localStorage under the key runash_voice_v2, read once on mount and rewritten on every change — each read and write is wrapped in a try/catch so a blocked or full storage quota never breaks the widget.
| Setting | Default | Effect |
|---|---|---|
| useRealAPI | off | Off uses canned per-persona fallback replies; on streams from /api/chat. |
| continuousMode | off | Reopens the mic automatically after each spoken reply. |
| showTranscript | on ≥700px | Shows the message history panel alongside the orb. |
| talkMode | tap | tap toggles listening on/off; hold listens only while the orb is pressed. |
| inputMode | voice | Falls back to text automatically when SpeechRecognition isn't available. |
| voiceOverride | none | Pins a specific system voice instead of matching the persona's default fragment. |
| rateOverride / pitchOverride | persona default | 0.6–1.6 range, overrides the active persona's speed/pitch. |
| volumeOverride | 0.95 | 0–1 range for spoken output. |
Keyboard shortcuts
Available whenever the widget has focus.
| Space | Start or stop talking to the orb. |
| Esc | Stop the current recording or playback. |
| T | Toggle between voice mode and text mode. |
Browser support
Speech recognition and speech synthesis have very different support levels — plan the text fallback around this.
The component detects support itself on mount and flips inputMode to text automatically — you don’t need to branch on navigator anywhere in your own code.
Security notes
What stays server-side, and what doesn't.
ANTHROPIC_API_KEYis read only inside/api/chat— the component never sees it and never should.- Microphone audio is processed locally by the browser’s own recognition engine; raw audio is never sent to your server or to Anthropic — only the resulting transcript text is.
- Settings stored in
localStorageare non-sensitive (voice preferences, toggles) — no credentials belong there. - Apply the same rate limiting to
/api/chatthat you’d use for any other AI endpoint before shipping this to real users.
Troubleshooting
The failures you'll actually hit, and the fix for each.