AniwaffleDocsHomeStudio

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

EndpointText inputAudio outputUse it for
POST /v1/ttsComplete text in one requestOne audio file in the response bodyNotifications, prompts, previews, files
WSS /v1/tts/streamText segments sent as they arriveAudio chunks while generation runsVoice agents, LLM replies, live playback
POST /v1/tts/jobsComplete text in one requestA file you download laterLong 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.

  1. Connect to wss://aniwaffle.com/v1/tts/stream with your API key in the Authorization header, or with a stream token in the token query parameter.
  2. Send start once, with the voice, the output format and optional model.
  3. Send text events as text becomes available. Segments are joined in the order you send them.
  4. Send flush (optional) to generate the text received so far without ending the request.
  5. Receive audio events. Each carries a base64 chunk and a seq number starting at 1.
  6. Send stop when there is no more text. Remaining text is generated.
  7. Receive usage and finish. The server then closes the connection. If the request fails, you receive one error event instead of finish.

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:

json
{"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 flush or stop.
  • stop generates any remaining text, so you don't need a final flush.

Play audio as it arrives

  • Decode each audio chunk from base64 and queue it in seq order. Chunks of one request always share the same format and channel count.
  • Read format from the event to choose the decoder. PCM chunks have no header; feed them to a PCM player at the format's sample rate.
  • Treat finish as 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.

Contact our team

Tell us about your character and what you’d like to build.