Complete TypeScript for the streaming pipeline in the Anatomy diagram. Drop your voice ID and key in; the scheduler works for any chunked-PCM source, not just ElevenLabs.
// ElevenLabs WebSocket streaming -> Web Audio scheduling (TypeScript)
// PCM route: request pcm_44100 and schedule raw Float32 chunks gap-free.
const VOICE = 'YOUR_VOICE_ID';
const ctx = new AudioContext({ sampleRate: 44100 });
let playhead = 0; // absolute schedule time in ctx time
const LEAD = 0.15; // s of jitter buffer before first chunk plays
function scheduleChunk(f32: Float32Array) {
const buf = ctx.createBuffer(1, f32.length, 44100);
buf.copyToChannel(f32, 0);
const src = ctx.createBufferSource();
src.buffer = buf;
src.connect(ctx.destination); // or into your DSP chain input node
if (playhead < ctx.currentTime + 0.02) playhead = ctx.currentTime + LEAD;
src.start(playhead);
playhead += buf.duration; // back-to-back, sample-accurate
}
function pcm16ToF32(bytes: Uint8Array): Float32Array {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const out = new Float32Array(bytes.byteLength / 2);
for (let i = 0; i < out.length; i++) out[i] = view.getInt16(i * 2, true) / 32768;
return out;
}
export function streamTTS(text: string, apiKey: string) {
const ws = new WebSocket(
`wss://api.elevenlabs.io/v1/text-to-speech/${VOICE}/stream-input` +
`?model_id=eleven_multilingual_v2&output_format=pcm_44100`
);
ws.onopen = () => {
ws.send(JSON.stringify({ text: ' ', xi_api_key: apiKey })); // handshake
ws.send(JSON.stringify({ text, try_trigger_generation: true }));
ws.send(JSON.stringify({ text: '' })); // EOS
};
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data);
if (msg.audio) {
const bytes = Uint8Array.from(atob(msg.audio), (c) => c.charCodeAt(0));
scheduleChunk(pcm16ToF32(bytes));
}
if (msg.isFinal) ws.close();
};
}