TTS streaming allows you to play audio as it’s being synthesized, providing faster time-to-first-audio for long text. This is especially useful for reading long articles or generating AI responses.
import { RunAnywhere } from '@runanywhere/core'// Stream synthesis with callbackawait RunAnywhere.synthesizeStream( 'This is a longer piece of text that will be synthesized and streamed in chunks for faster playback.', { rate: 1.0 }, (chunk) => { // Each chunk contains partial audio console.log('Got chunk:', chunk.numSamples, 'samples') playChunk(chunk.audio, chunk.sampleRate) })
interface TTSOutput { /** Base64-encoded audio chunk (float32 PCM) */ audio: string /** Sample rate in Hz */ sampleRate: number /** Number of samples in this chunk */ numSamples: number /** Duration of this chunk in seconds */ duration: number /** Whether this is the final chunk */ isFinal: boolean}
For smooth playback, manage an audio queue using the SDK’s Audio utility:
import { RunAnywhere, TTSOutput } from '@runanywhere/core'class AudioQueuePlayer { private queue: TTSOutput[] = [] private isPlaying = false enqueue(chunk: TTSOutput) { this.queue.push(chunk) if (!this.isPlaying) { this.playNext() } } private async playNext() { if (this.queue.length === 0) { this.isPlaying = false return } this.isPlaying = true const chunk = this.queue.shift()! // Convert float32 PCM to WAV and play const wavBase64 = RunAnywhere.Audio.createWavFromPCMFloat32(chunk.audio, chunk.sampleRate) await RunAnywhere.Audio.playAudio(wavBase64) // Play next chunk this.playNext() } async stop() { this.queue = [] this.isPlaying = false await RunAnywhere.Audio.stopPlayback() }}// Usageconst player = new AudioQueuePlayer()await RunAnywhere.synthesizeStream(longText, { rate: 1.0 }, (chunk) => player.enqueue(chunk))
AudioContext / Web Audio API does not work in React Native. Always use
RunAnywhere.Audio.createWavFromPCMFloat32() to convert TTS output before playback.
Streaming provides faster time-to-first-audio (TTFA) for long text. For short phrases (< 100 characters), the overhead may not be worth it — use synthesize() instead.