Before you start
- Open your running Velosyll studio and sign in as the workspace owner. The examples use the selected project's processing credits.
- Use a browser with Web Audio and an available audio output.
1. Open the runnable example
Choose Open runnable example to use the signed-in, same-origin demo. To integrate the source into your own application, download its files and serve the SDK and capture worklet on your origin. Point getToken to your authenticated backend.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Streaming speech</title>
<main>
<h1>Streaming speech</h1>
<fieldset><legend>Spoken output</legend><label>Language <select id="language"></select></label> <label>Stock voice <select id="language-voice"></select></label></fieldset><label>Text <textarea id="text" dir="auto">Welcome to the studio.</textarea></label>
<button id="start">Speak</button>
<button id="finish" disabled>Finish</button>
<button id="cancel" disabled>Cancel</button>
<p id="status" role="status">Ready</p>
<p id="partial"></p>
<div id="output" aria-live="polite"></div>
</main>
<script type="module" src="./main.js"></script>
</html>export function controls(open, manualFinish = true) {
const start = document.querySelector("#start");
const finish = document.querySelector("#finish");
const cancel = document.querySelector("#cancel");
const status = document.querySelector("#status");
let controller;
finish.hidden = !manualFinish;
const cancelRun = () => controller?.abort();
cancel.onclick = cancelRun;
window.addEventListener("pagehide", cancelRun);
start.onclick = async () => {
if (controller) return;
const run = new AbortController();
controller = run;
start.disabled = true;
cancel.disabled = false;
status.textContent = "Connecting…";
try {
const session = await open(run.signal);
status.textContent = "Connected";
finish.disabled = !manualFinish;
finish.onclick = () => {
finish.disabled = true;
status.textContent = "Finishing…";
session.stop().catch(() => {}); // The same failure reaches session.done.
};
const result = await session.done;
status.textContent = result.id ? "Saved recording " + result.id : "Finished";
} catch (error) {
status.textContent = run.signal.aborted ? "Cancelled" : error.message;
} finally {
run.abort();
controller = undefined;
start.disabled = false;
cancel.disabled = finish.disabled = true;
}
};
}2. Authorize one connection
The browser exchanges its signed-in owner session for a 60-second token scoped to listen, interpret or speech as requested by the SDK. Expiry controls when a new connection may start. For a separate web application, host the SDK and capture worklet on its origin. Have its authenticated backend check the user's permission for the project and operation, then call POST /v1/client-tokens with that project's server-side bearer key. Return only the scoped token with Cache-Control: no-store. The local studio accepts cross-origin sockets with an explicit scoped token.
import { SpeechClient } from "/sdk/browser/index.js";
export const client = new SpeechClient({
baseURL: location.origin,
async getToken(scope) {
const response = await fetch("/v1/client-tokens", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ scope, expires_in: 60 }),
});
if (!response.ok) throw Error("Stream authorization failed (" + response.status + ").");
return (await response.json()).token;
},
});3. Queue the returned audio for playback
Each audio_start describes the next phrase's channel count and sample rate. Binary frames between audio_start and audio_end contain raw mono signed 16-bit little-endian samples. Schedule each buffer after the previous buffer and use its announced sample rate. The remote done event can arrive before the final sound reaches the speakers.
export function pcmPlayer(context) {
let rate = 0;
let until = 0;
const playing = new Map();
return {
get busy() { return context.currentTime < until; },
event(frame) {
if (frame.type === "audio_end") rate = 0;
if (frame.type !== "audio_start") return;
if (frame.format !== "s16le" || frame.channels !== 1 || !(frame.sample_rate > 0))
throw Error("Unsupported audio format.");
rate = frame.sample_rate;
},
audio(bytes) {
if (!rate || !bytes.byteLength || bytes.byteLength % 2) throw Error("Invalid PCM frame.");
const data = new DataView(bytes);
const audio = context.createBuffer(1, bytes.byteLength / 2, rate);
const samples = audio.getChannelData(0);
for (let i = 0; i < samples.length; i++) samples[i] = data.getInt16(i * 2, true) / 32768;
const source = context.createBufferSource();
source.buffer = audio;
source.connect(context.destination);
let ended;
const done = new Promise(resolve => { ended = resolve; });
const release = () => { source.disconnect(); playing.delete(source); ended(); };
playing.set(source, { done, release });
source.onended = release;
const start = Math.max(context.currentTime + 0.025, until);
until = start + audio.duration;
source.start(start);
},
drain() { return Promise.all([...playing.values()].map(item => item.done)); },
cancel() {
for (const [source, item] of playing) {
source.onended = null;
source.stop();
item.release();
}
until = 0;
},
};
}4. Send text, flush and finish
Select a language and stock voice and enter text in the selected language. Click Speak to unlock audio from a user gesture. The SDK opens /v1/speech/stream with a speech-scoped token, then waits for ready. Each sendText call appends text. flush requests audio for any pending phrase; finish drains the connection. You can send additional fragments before finish. This example uses the default single-stream binary transport. For multiplexed synthesis, set language and voice for each lane when you open it. Route that lane’s JSON base64 audio_chunk frames to its own player.
export async function loadVoiceMenus(initialLanguages) {
const start = document.querySelector("#start");
start.disabled = true;
try {
const response = await fetch("/v1/stock-voices");
if (!response.ok) throw Error("Cannot load the stock voice catalog.");
const { items } = await response.json();
const names = new Intl.DisplayNames(["en"], { type: "language" });
const codes = [...new Set(items.map(voice => voice.language))]
.sort((a, b) => names.of(a).localeCompare(names.of(b)));
if (!codes.length) throw Error("No stock voices are installed.");
for (const [id, initial] of Object.entries(initialLanguages)) {
const language = document.getElementById(id);
const select = document.getElementById(id + "-voice");
language.replaceChildren(...codes.map(code => new Option(names.of(code), code)));
language.value = codes.includes(initial) ? initial : codes[0];
const refresh = () => {
const voices = items.filter(voice => voice.language === language.value);
select.replaceChildren(...voices.map(voice => {
const name = voice.name || voice.id;
const gender = voice.gender && voice.gender !== "unspecified" ? " · " + voice.gender : "";
return new Option(name + gender, voice.id);
}));
};
language.addEventListener("change", refresh);
refresh();
}
start.disabled = false;
} catch (error) {
document.querySelector("#status").textContent = error.message;
}
}import { client } from "./client.js";
import { controls } from "./controls.js";
import { pcmPlayer } from "./player.js";
import { loadVoiceMenus } from "./voices.js";
await loadVoiceMenus({ language: "en" });
controls(async signal => {
const language = document.querySelector("#language").value;
const voice = document.querySelector("#language-voice").value;
const text = document.querySelector("#text").value.trim();
if (!text || [...text].length > 3000) throw Error("Enter 1–3,000 characters.");
const context = new AudioContext();
const player = pcmPlayer(context);
let stream;
const silence = () => player.cancel();
signal.addEventListener("abort", silence, { once: true });
try {
await context.resume();
stream = await client.open("speech", { language, voice }, {
signal, onEvent: frame => player.event(frame), onAudio: bytes => player.audio(bytes),
});
stream.sendText(text);
stream.flush();
const done = stream.finish().then(async result => { await player.drain(); return result; });
return { done: done.finally(close) };
} catch (error) {
stream?.abort();
await close();
throw error;
}
async function close() {
signal.removeEventListener("abort", silence);
player.cancel();
if (context.state !== "closed") await context.close();
}
}, false);Expected result
The page speaks the entered text, drains scheduled playback after the socket's done event, then releases its audio context. Cancel stops queued playback and cancels an open socket.
Troubleshooting
- Authorization returned 401 or 403.
- Sign in as the workspace owner on the exact origin serving the example. For a member-only first-party UI, use the SDK's same-origin useStudioSession mode. A separate application needs a protected server-side token issuer.
- The audio sounds distorted or plays at the wrong speed.
- Decode each binary block as little-endian signed PCM, use audio_start.sample_rate for the phrase and schedule adjacent buffers in arrival order.