Skip to content

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.

  • 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.

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 (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. WebAPI plays global only.
  • Dependent props. Changing provider clears language and voice; changing language clears voice. 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.
getCapabilities(signal) Resolves the provider’s offer: languageMode, defaultLanguage, defaultVoice, languages ({ id, name, defaultVoice? }) and voices ({ id, name, language? }). Reads metadata only; it never loads a voice.
subscribeCapabilities(listener) 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 (comp-ai-speech-to-text, AISpeechToTextComponent) recognizes speech. It does two jobs:

  • 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 sources select, 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-speech', 'microphone'] 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-speech' This agent’s own speech.
'runtime-audio' 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-audio' 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?, onPartial? }) Recognize a finished recording and resolve its text. audio is a Blob, a microphone clip, or mono { pcm, sampleRate }. Up to five minutes.
createSession(listener, { input?, signal? }) Resolve a live session: push(frame) feeds audio frames, finish() flushes the rest and waits for the text, stop() discards it.
subscribeTranscripts(listener) 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.
getCapabilities(signal) 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 when sources lacks '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 (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.

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.

BrowserVoice.jx
#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();
});
}
  • getCapabilities reads the provider’s offer without loading a voice. Browsers often load their voices late, so the count can be 0 at first; subscribeCapabilities tells you when the list changes.
  • The line is spoken from a button press, which unlocks the browser’s audio.
  • speak resolves when the line ends and rejects when it is stopped or replaced, so pressing the button again mid-line logs “Speech stopped”.
  • WebAPI speech always plays global: it does not come from the agent’s position.
KioskWelcome.jx
#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.
  • speak resolves when the line ends and rejects when it is stopped or replaced, so the try/catch also catches a second press interrupting the first.
  • This speech does not go through the conversation: no prompt or reply is added to the chat.
GuideVoice.jx
#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);
}
}
  • positional makes the agent’s voice come from where it stands and fade past refDistance, so two agents in one room sound apart.
  • getCapabilities needs a signal; an AbortController lets you cancel the request, for example when a voice menu closes.
  • Setting voice after audio and volume keeps it: only provider and language clear the voice.
PushToTalk.jx
#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 until stop(), which resolves the clip.
  • transcribe(clip, { input: 'microphone' }) recognizes the clip. Marking it as microphone input requires 'microphone' in the component’s sources.
  • Recognition never prompts the agent by itself: the script sends the text, and checks activeTurnId first so it never sends while a turn is running.
TranscriptLog.jx
#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();
}
  • subscribeTranscripts follows the same text the captions show, without starting any recognition.
  • Only final lines 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.
  • 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.send itself.
  • Using { input: 'microphone' } without the source. The call rejects at once. Add 'microphone' to the component’s sources.
  • Leaving the microphone on. Call Input.microphone.stop() when you are done; the browser’s recording indicator stays on while any script listens.
  • Setting voice before language. Changing language clears voice. Set both in one setProps call, or the language first.
  • Forgetting to release subscriptions. Stop subscribe, subscribeCapabilities and subscribeTranscripts listeners in dispose.