Speech
Updated
Three components give an agent a voice and ears. AI Text To Speech speaks text aloud: the agent’s replies, or any line a script gives it. AI Speech To Text recognizes speech: the visitor’s microphone when they press Mic, and audio playing in the scene for captions. AI Speech Capture marks which scene audio is worth transcribing. Each speech component picks its own provider, so an agent can listen with one service and speak with another.
Before you start
Section titled “Before you start”- You have an agent; see Creating an agent. The dialog’s Play button and Mic are described in Dialog and captions.
- Speech plays through the scene’s audio listener, like any other sound. Distance and audio zones work as in Audio.
- Browsers keep a page silent until the visitor first clicks, taps or presses a key. Code that speaks should run from a user action.
Providers
Section titled “Providers”Both speech components have a provider prop:
| Provider | Speaks | Recognizes | What it is |
|---|---|---|---|
'Local' (default) |
yes | yes | Models that run on the visitor’s device. The first use downloads and prepares the model. |
'Remote' |
yes | yes | The speech service the application provides. |
'WebAPI' |
yes | no | The browser’s built-in speech synthesis. Voices differ between devices. |
The inspector may list further providers that the application supports.
AI Text To Speech
Section titled “AI Text To Speech”AI Text To Speech (comp-ai-text-to-speech, AITextToSpeechComponent) speaks text. It speaks the agent’s replies when the dialog’s autoSpeak is on or the visitor presses Play, and any text a script passes to speak.
| Prop | Type | Default | Description |
|---|---|---|---|
provider |
string | 'Local' |
Who generates the speech. |
language |
string | '' |
Language id of the provider. Empty uses the provider’s default or automatic detection. |
voice |
string | '' |
Voice id of the provider. Empty uses the language’s default voice. |
volume |
number | 1 |
Gain, 0 to 1. Changes apply to speech already playing. |
audio |
'global' or 'positional' |
'global' |
global plays at full level everywhere; positional plays from the agent and fades with distance. |
refDistance |
number, m | 1 |
For positional: the distance within which speech is at full level. |
- Positional speech uses the inverse distance model, like a Positional Audio source, and respects audio zones.
WebAPIplays global only. - Dependent props. Changing
providerclearslanguageandvoice; changinglanguageclearsvoice. Changing the provider, language, voice or audio stops the current playback; changing the volume does not. - Audio unlock. Automatic speech never unlocks the browser’s audio by itself. Until the visitor interacts with the page, the dialog asks them to enable audio or press Play. Pressing Play unlocks it.
| Member | What it does |
|---|---|
speak(utterance?, { audio?, signal? }) |
Speak { text }, replacing anything playing. Resolves when playback ends; rejects when it fails, is stopped or is replaced. With no utterance, speaks the last one again. audio overrides the component for this line. |
play(utterance?, options?) |
The same as speak. |
stop() |
Stop playback. |
pause(), resume() |
Pause and resume. pause() throws when the provider cannot pause. |
playing, canPause, utterance |
Read only: whether it is playing, whether it can pause, and the current { text }. |
getSnapshot() |
{ phase, utterance?, error?, progress? }, with phase one of idle, loading, playing, paused, error. progress reports the download of a Local model. |
subscribe(listener) |
Call listener() when the snapshot changes. Returns the function that stops it. |
get |
Resolves the provider’s offer: languageMode, default, defaultVoice, languages ({ id, name, default) and voices ({ id, name, language? }). Reads metadata only; it never loads a voice. |
subscribe |
Call listener() when that list changes, for example when the browser’s voices arrive. Returns the stop function. |
When a reply actually starts playing, the agent sends AIAgent::talking. A failed attempt to speak a reply sends AIAgent::error, and the text reply stays complete.
AI Speech To Text
Section titled “AI Speech To Text”AI Speech To Text (comp-ai-speech-to-text, AISpeechToTextComponent) recognizes speech. It does two jobs:
An AI Caption shows what the guide's AI Speech To Text hears: her own lines spoken through the browser's voice, and the Radio, which an AI Speech Capture marker selects for transcription.
Press Next line: the guide speaks with your browser's voice and her caption appears above her, also in the log. Transcribing the Radio needs the AI service, which this preview does not have: the log reports it instead. Drag outside the panel to orbit the camera.
- Voice input. When the visitor presses Mic in the dialog, it recognizes what they say and sends it to the agent as a prompt.
- Transcription. It transcribes the audio its
sourcesselect, for captions and for the agent’s Context. Transcription never sends a prompt.
| Prop | Type | Default | Description |
|---|---|---|---|
provider |
string | 'Local' |
Who recognizes the speech. |
sources |
array | ['agent- |
What it listens to; see the table below. [] transcribes nothing automatically. |
silenceMs |
integer, ms | 700 |
Trailing silence that ends a spoken phrase, 0 to 5000. |
persist |
boolean | true |
Store finished transcripts in the agent’s Context. Off, recognition and captions still work and nothing is stored. |
language |
string | '' |
Language hint. Empty detects it automatically. |
| Source | What it covers |
|---|---|
'agent- |
This agent’s own speech. |
'runtime- |
Audio playing in the scene: Audio, Ambisonic Audio, Video and UI Video sources, and agent speech. Never the microphone. AI Speech Capture markers narrow it. |
'streaming- |
Live streams playing in the scene. |
'microphone' |
The visitor’s microphone, only while it is explicitly started: by the dialog’s Mic, or by a script passing { input: 'microphone' }. |
Sources add up, and audio covered twice is processed once. When the runtime already knows the text of a sound, such as the agent’s own speech, it uses that text instead of recognizing the audio. Selecting 'microphone' only allows voice input: it never opens the microphone or asks permission by itself.
Interrupting. In voice mode, once the agent starts answering, at least a quarter of a second of confirmed speech cancels its reply and speech, and the new phrase is sent after the trailing silence. Short noises do not interrupt.
| Member | What it does |
|---|---|
transcribe(audio, { input?, signal?, on |
Recognize a finished recording and resolve its text. audio is a Blob, a microphone clip, or mono { pcm, sample. Up to five minutes. |
create |
Resolve a live session: push(frame) feeds audio frames, finish() flushes the rest and waits for the text, stop() discards it. |
subscribe |
Follow the agent’s transcripts, the same text the captions show. Starts nothing. Returns the stop function. |
getSnapshot(), subscribe(listener) |
{ phase }, idle or transcribing, and its changes. |
get |
Resolves the provider’s languages. |
Transcript listeners receive { type: 'text', sourceId, text, final }, { type: 'clear', sourceId } or { type: 'error', sourceId, message }. final is true for a finished phrase and false for a guess still being refined.
{ input: 'microphone' }rejects at once whensourceslacks'microphone'.- Recognized text also goes to the captions and, with
persist, to the agent’s Context. - Recognition never sends a prompt. A script decides whether to call
conversation.send(text).
AI Speech Capture
Section titled “AI Speech Capture”AI Speech Capture (comp-ai-speech-capture, AISpeechCaptureComponent) is a marker with no props. Put it on audio entities to choose which ones the 'runtime-audio' source transcribes:
- With no enabled marker anywhere,
'runtime-audio'covers all eligible scene audio. - With at least one enabled marker, it covers only the marked entities.
A marker applies to its own entity, not to its children. It does not affect 'agent-speech' or 'streaming-audio', and every listening agent shares the same markers. It never captures audio itself.
Examples
Section titled “Examples”1. Speak with the browser’s voice
Section titled “1. Speak with the browser’s voice”With the WebAPI provider, AI Text To Speech uses the voices built into the browser, so it speaks with no AI service at all. A UI button speaks a line; at startup the script logs how many voices the browser offers.
#pragma lifecycle(startup)
let voice;
async function listVoices() { try { const offer = await voice.getCapabilities(new AbortController().signal); log('Voices offered by this browser:', offer.voices.length); } catch (error) { log('Could not read the voices:', error.message); }}
async function welcome() { try { await voice.speak({ text: 'Welcome to the gallery. Ask me anything about the paintings.' }); log('Finished speaking.'); } catch (error) { log('Speech stopped:', error.message); }}
function startup() { voice = findEntity('Guide').getComponent(AITextToSpeechComponent); log('Speaking with the', voice.props.provider, 'provider'); listVoices();
on('kiosk/speak', (event) => { if (event.eventType === EventType.UIButton.Press) welcome(); });}An AI agent's Text To Speech on the WebAPI provider speaks a line when a UI button is pressed, using the browser's own voices: no AI service is needed.
Press Speak to hear the guide. The voices are the browser's own, so they differ between browsers and systems. Drag to orbit the camera, scroll to zoom.
getCapabilitiesreads the provider’s offer without loading a voice. Browsers often load their voices late, so the count can be0at first;subscribeCapabilitiestells you when the list changes.- The line is spoken from a button press, which unlocks the browser’s audio.
speakresolves when the line ends and rejects when it is stopped or replaced, so pressing the button again mid-line logs “Speech stopped”.WebAPIspeech always playsglobal: it does not come from the agent’s position.
Snippets
Section titled “Snippets”1. Speak a line on a button press
Section titled “1. Speak a line on a button press”#pragma lifecycle(startup)
// Scene: an AI Agent named "Guide" with AI Text To Speech,// and a UI Button with a Signal Emitter on 'kiosk/welcome'.let voice;
async function welcome() { try { await voice.speak({ text: 'Welcome to the east wing. Ask me anything about the paintings.' }); log('Finished speaking.'); } catch (error) { log('Speech stopped:', error.message); }}
function startup() { voice = findEntity('Guide').getComponent(AITextToSpeechComponent); on('kiosk/welcome', (event) => { if (event.eventType === EventType.UIButton.Press) welcome(); });}- The line is spoken from a button press, a user action, so the browser’s audio is unlocked.
speakresolves when the line ends and rejects when it is stopped or replaced, so thetry/catchalso catches a second press interrupting the first.- This speech does not go through the conversation: no prompt or reply is added to the chat.
2. Choose a voice and make it positional
Section titled “2. Choose a voice and make it positional”#pragma lifecycle(startup)
// Scene: an AI Agent named "Guide" with AI Text To Speech.async function startup() { const voice = findEntity('Guide').getComponent(AITextToSpeechComponent); voice.setProps({ audio: 'positional', refDistance: 2, volume: 0.9 });
const controller = new AbortController(); try { const offer = await voice.getCapabilities(controller.signal); log('Languages:', offer.languages.map((language) => language.id).join(', ')); const english = offer.voices.find((v) => v.language && v.language.startsWith('en')); if (english) { voice.setProps({ voice: english.id }); log('Using voice', english.name); } } catch (error) { log('Could not read the voices:', error.message); }}positionalmakes the agent’s voice come from where it stands and fade pastrefDistance, so two agents in one room sound apart.getCapabilitiesneeds a signal; anAbortControllerlets you cancel the request, for example when a voice menu closes.- Setting
voiceafteraudioandvolumekeeps it: onlyproviderandlanguageclear the voice.
3. Push to talk
Section titled “3. Push to talk”#pragma lifecycle(startup)
// Scene: an AI Agent named "Guide" with AI Speech To Text whose sources include 'microphone',// and two UI Buttons with Signal Emitters on 'talk/start' and 'talk/stop'.let stt;let conversation;let recording;
async function stopAndAsk() { if (!recording) return; const clip = await recording.stop(); recording = undefined; Input.microphone.stop();
const text = await stt.transcribe(clip, { input: 'microphone' }); if (!text.trim()) return log('Heard nothing.'); if (conversation.getSnapshot().activeTurnId) return log('The guide is still answering.'); await conversation.send(text);}
function startup() { const guide = findEntity('Guide'); stt = guide.getComponent(AISpeechToTextComponent); conversation = guide.getComponent(AIModelComponent).getConversation(); if (!conversation) return;
on('talk/start', (event) => { if (event.eventType === EventType.UIButton.Press) recording = Input.microphone.record(); }); on('talk/stop', (event) => { if (event.eventType !== EventType.UIButton.Press) return; stopAndAsk().catch((error) => log('Could not understand:', error.message)); });}Input.microphone.record()starts the microphone (asking permission the first time) and records untilstop(), which resolves the clip.transcribe(clip, { input: 'microphone' })recognizes the clip. Marking it as microphone input requires'microphone'in the component’ssources.- Recognition never prompts the agent by itself: the script sends the text, and checks
activeTurnIdfirst so it never sends while a turn is running.
4. Log live transcripts
Section titled “4. Log live transcripts”#pragma lifecycle(startup, dispose)
// Scene: an AI Agent named "Guide" with AI Text To Speech and// AI Speech To Text whose sources include 'agent-speech' and 'runtime-audio'.// The scene's narration Audio entity carries an AI Speech Capture marker.let stopTranscripts;const lines = [];
function startup() { const stt = findEntity('Guide').getComponent(AISpeechToTextComponent); stopTranscripts = stt.subscribeTranscripts((event) => { if (event.type === 'text' && event.final) { lines.push(event.text); log(`[${event.sourceId}]`, event.text); } if (event.type === 'error') log('Transcription problem:', event.message); });}
function dispose() { if (stopTranscripts) stopTranscripts();}subscribeTranscriptsfollows the same text the captions show, without starting any recognition.- Only
finallines are kept; partial lines change as recognition refines them. - Because the narration carries an AI Speech Capture marker,
'runtime-audio'transcribes only that entity, not every sound in the scene.
Common mistakes
Section titled “Common mistakes”- Speaking before the first interaction. Browsers keep audio locked until a click, tap or key press. Speak from a user action, or let the visitor press Play.
- Expecting recognition to prompt the agent. Only the dialog’s Mic sends what it hears. A script that transcribes must call
conversation.senditself. - Using
{ input: 'microphone' }without the source. The call rejects at once. Add'microphone'to the component’ssources. - Leaving the microphone on. Call
Input.microphone.stop()when you are done; the browser’s recording indicator stays on while any script listens. - Setting
voicebeforelanguage. Changinglanguageclearsvoice. Set both in onesetPropscall, or the language first. - Forgetting to release subscriptions. Stop
subscribe,subscribeCapabilitiesandsubscribeTranscriptslisteners indispose.