Text to Speech
Streaming
Stream text in and audio out over one WebSocket, so playback starts while the text is still being written, for example token by token from an LLM.
Choose an endpoint
| Endpoint | Text input | Audio output | Use it for |
|---|---|---|---|
POST /v1/tts | Complete text in one request | One audio file in the response body | Notifications, prompts, previews, files |
WSS /v1/tts/stream | Text segments sent as they arrive | Audio chunks while generation runs | Voice agents, LLM replies, live playback |
POST /v1/tts/jobs | Complete text in one request | A file you download later | Long text, batch work, background processing |
All three use the same voices, models, tags, output formats and credits.
How a stream works
Each WebSocket connection carries one request. Messages are JSON text frames.
- Connect to
wss://aniwaffle.com/v1/tts/streamwith your API key in theAuthorizationheader, or with a stream token in thetokenquery parameter. - Send
startonce, with the voice, the output format and optional model. - Send
textevents as text becomes available. Segments are joined in the order you send them. - Send
flush(optional) to generate the text received so far without ending the request. - Receive
audioevents. Each carries a base64 chunk and aseqnumber starting at 1. - Send
stopwhen there is no more text. Remaining text is generated. - Receive
usageandfinish. The server then closes the connection. If the request fails, you receive oneerrorevent instead offinish.
Valid client order: start → text… → (flush → text…)… → stop. For the next utterance, open a new connection.
Example
This client streams one sentence, collects the chunks in order and writes the audio to a file.
// npm install ws
import { writeFile } from 'node:fs/promises'
import WebSocket from 'ws'
const socket = new WebSocket('wss://aniwaffle.com/v1/tts/stream', {
headers: { Authorization: `Bearer ${process.env.ANIWAFFLE_API_KEY}` },
handshakeTimeout: 10_000,
})
const chunks: Buffer[] = []
socket.on('open', () => {
socket.send(JSON.stringify({
event: 'start',
request: { voice_id: process.env.ANIWAFFLE_VOICE_ID, output_format: 'pcm_48000' },
}))
socket.send(JSON.stringify({ event: 'text', text: 'Hello! ' }))
socket.send(JSON.stringify({ event: 'text', text: 'This audio started before the text was finished.' }))
socket.send(JSON.stringify({ event: 'stop' }))
})
socket.on('message', async (data) => {
const event = JSON.parse(data.toString())
if (event.event === 'audio') {
chunks[event.seq - 1] = Buffer.from(event.audio, 'base64')
} else if (event.event === 'error') {
console.error(`${event.code}: ${event.detail}`)
socket.close()
} else if (event.event === 'finish') {
await writeFile('speech.pcm', Buffer.concat(chunks))
console.log('Saved speech.pcm, request', event.request_id)
}
})speech.pcm is raw 16-bit mono PCM at 48 kHz. See Output formats to play it or save it as WAV.
Stream text from an LLM
Forward the model's output as text events, and flush at natural phrase boundaries:
{"event":"text","text":"Your order is ready, "}
{"event":"flush"}
{"event":"text","text":"and it will arrive tomorrow."}
{"event":"stop"}- Flush whole phrases. Flush after a clause or sentence, not after every token. Smaller pieces start audio sooner but give the model less context for natural intonation.
- Keep spacing and punctuation. Text is joined exactly as sent, so include the spaces and punctuation that belong between segments.
- Close tags before flushing. A paired tag must be closed before
flushorstop. stopgenerates any remaining text, so you don't need a finalflush.
Play audio as it arrives
- Decode each
audiochunk from base64 and queue it inseqorder. Chunks of one request always share the sameformatand channel count. - Read
formatfrom the event to choose the decoder. PCM chunks have no header; feed them to a PCM player at the format's sample rate. - Treat
finishas the end of generation. Playback can still be running; mark it complete when your player drains, not when the socket closes.
Interruptions
To stop speech when the user interrupts, close the WebSocket and discard queued audio. Generation stops. If audio was already delivered, the characters received so far are billed.
A failed request ends with an error event. If retryable is true, retry on a new connection after a backoff. Audio from the failed attempt may already have played, so decide whether to replay the whole utterance or continue from a sentence boundary. See Errors.
Stream to browsers and mobile apps
Clients must not hold your API key. Your server creates a stream token, and the client connects with ?token=. Browser origins must be on your workspace's allowlist.
Reference
See Stream speech for every event and field.