Voice-Swap logo
Our RosterPricingEnterpriseYour ModelBlogFAQContact
Dashboard

Voice-Swap API / Streaming TTS

Streaming TTS (WebSocket)

Send text and get speech back as it's generated, over one WebSocket connection that can carry many turns. It's built for voice agents and other live conversations: start sending text before you have all of it, start playing audio before the turn is finished, and interrupt when the listener talks over it.

wss://api.voice-swap.ai/v1/tts/stream

Access and billing

Streaming TTS isn't self-serve yet: we set it up for Enterprise customers. Your team needs a streaming allowance, or your personal account streaming minutes, before you can connect. Contact us to get access.

  • Streaming is billed by connection time, from your streaming minutes. It doesn't use credits or TTS characters.
  • Time is charged in 30-second blocks, each at its start: the first just before you receive ready, then every 30 seconds until the connection closes. A connection that gets that far is charged at least 30 seconds, even if it closes before ready arrives.
  • You are charged while the connection is open, even when nothing is being spoken. Close it when you are done.
  • Streams opened by a team member, or with a team's API key, use the team's allowance, which resets each month.
  • When a team runs out, what happens depends on its plan: either the stream carries on and the extra minutes are added to that month's invoice, or it stops as below.
  • Otherwise, when your balance can't cover the next block you get { "error": "insufficient_balance" } and the connection closes with 1008 Insufficient balance.
  • A team without a streaming allowance is refused with 1008 Streaming not enabled. A team without enough balance for the first block, or a personal account without enough streaming minutes, is refused with 1008 Insufficient balance. Teams with overage are never refused for balance.
  • If we can't charge a block on our side, the connection closes with 1011 rather than carrying on unbilled. Reconnect.
  • Recovering from an upstream_reset doesn't start a new charge.

Connecting

Authenticate with an access token in the Authorization header, the same token you use for the REST API. See Authentication in the API documentation to create one. Connect from your server: browser WebSocket APIs can't set this header, and access tokens shouldn't be shipped to browsers. Relay the audio to your own clients from there.

  • Pass zero_shot_model_id, the id of one of your Instant Voice Clones from GET /v1/tts/zero-shot-models, as a query parameter.
  • Wait for { "ready": true } before sending anything. Messages sent before it are ignored.
wss://api.voice-swap.ai/v1/tts/stream?zero_shot_model_id=507f1f77bcf86cd799439012
Authorization: Bearer <ACCESS_TOKEN>

Some requests are refused before the connection opens, with an HTTP status instead of a close code. Most WebSocket clients report this as a connection error (the ws package as "Unexpected server response").

Refused connections
HTTP statusMeaning
400Invalid query parameters, for example a missing or malformed zero_shot_model_id.
401The access token is missing, invalid or expired. Get a new one and reconnect.
503The service is restarting or temporarily unavailable. Reconnect after a short wait.

Messages

You send JSON text frames. A binary frame or invalid JSON closes the connection with 1008.

Messages you send
You sendMeaning
{ "text": "..." }Text for the current turn. Send it in as many pieces as you like, for example as your language model produces it.
{ "eot": true }End of turn: speak everything sent so far. The connection stays open for the next turn.
{ "eos": true }End of session: finish the current turn, then close the connection with 1000.
{ "eog": true }Interrupt: stop the audio being generated now. See Interrupting.

We send binary audio frames and JSON text frames.

Messages you receive
You receiveMeaning
Binary frameAudio for the current turn. See Audio format.
{ "ready": true }The connection is ready for text. Also sent again after an upstream_reset, once the stream has recovered.
{ "done": true }All of a turn's audio has been sent. After an interrupt it is { "done": true, "interrupted": true }.
{ "error": "<code>" }Something went wrong. See Errors.

Audio format

Binary frames are raw 16-bit signed little-endian mono PCM at 24 kHz, with no container or header. Play the frames as they arrive, or join them and add a WAV header to save a file.

Interrupting

Send { "eog": true } to stop the turn being generated, for example when the listener starts talking. Each eog gets exactly one { "done": true, "interrupted": true }, which marks where that audio ends. Your turn is over as soon as you send eog: text sent straight after it starts the next turn.

  • Audio is generated ahead of playback, and audio already sent can't be recalled. Clear your own playback buffer when you interrupt.
  • Drop all audio from sending eog until its interrupted done arrives. The turn you are hearing may already have finished generating, so you may see a plain done first.
  • The stop lands within about half a second. If it isn't answered within 10 seconds, you get upstream_reset instead, which also ends the wait.
  • At most 2 interrupts can be waiting for their done at once. A third closes the connection with 1008.

Errors

Errors arrive as { "error": "<code>" }. Most leave the connection open; those that close it say so below.

Error codes
CodeMeaning
turn_text_limit_exceededThe turn went over the text limit. The extra text is dropped and the turn continues. 10 in a row close the connection with 1008.
upstream_resetThe stream was interrupted and is recovering on the same connection. Wait for ready again. If turn_lost is true, that turn's audio was cut off: send its text again.
idle_timeoutNothing was sent either way for too long. The connection then closes with 1001. If turn_lost is true, that turn's audio was cut off: send its text again after reconnecting.
server_shutting_downThe server is restarting. The connection then closes with 1001: reconnect. If turn_lost is true, that turn's audio was cut off: send its text again after reconnecting.
insufficient_balanceYour streaming balance can't cover the next 30 seconds. The connection then closes with 1008. If turn_lost is true, that turn's audio was cut off: send its text again after topping up and reconnecting. See Access and billing.

Limits

Limits
LimitValueWhen you go over
Text per turn10 KB (10,240 bytes of UTF-8, not characters)turn_text_limit_exceeded; the turn continues. 10 in a row close with 1008.
Frame size64 KBClosed with 1009
Idle4.5 minutes with no message from you and no audio from usidle_timeout, then 1001
Connection lifetime1 hourThe connection drops (you see 1006). Reconnect to keep going.
Unanswered interrupts2 eogs waiting for their interrupted done1008 Too many interrupts
Concurrent connections20 per team by default (ask us to change it); 1 per personal account1008 Connection limit exceeded

Close codes

Close codes
CodeMeaning
1000Normal close after eos
1001Going away: idle timeout or server restart
1006Dropped without a close frame, for example at the 1-hour limit
1008Policy violation: no access to the voice (Model not found), the connection limit, streaming balance, another limit, or an invalid message
1009Frame over 64 KB
1011Internal error, including when recovery after an upstream_reset fails or a streaming charge can't be made. Reconnect.
1013Temporarily unavailable. Reconnect after a short wait.

Example: a two-turn session

This Node.js script (using the ws package) speaks two turns and saves the audio to output.pcm. Set VOICE_SWAP_ACCESS_TOKEN and VOICE_SWAP_VOICE_CLONE_ID (an Instant Voice Clone id) first.

import fs from 'node:fs'
import WebSocket from 'ws'

const url = new URL('wss://api.voice-swap.ai/v1/tts/stream')
url.searchParams.set('zero_shot_model_id', process.env.VOICE_SWAP_VOICE_CLONE_ID)

const ws = new WebSocket(url, {
  headers: { Authorization: `Bearer ${process.env.VOICE_SWAP_ACCESS_TOKEN}` },
})
const audio = fs.createWriteStream('output.pcm')
const turns = ['Hello, and thanks for calling.', 'How can I help you today?']
let started = false
let currentTurn
let resendTurn = false

const sendTurn = (text) => {
  currentTurn = text
  ws.send(JSON.stringify({ text }))
  ws.send(JSON.stringify({ eot: true }))
}

ws.on('message', (data, isBinary) => {
  if (isBinary) {
    audio.write(data) // 16-bit little-endian mono PCM at 24 kHz
    return
  }
  const message = JSON.parse(data.toString())
  if (message.ready && !started) {
    started = true
    sendTurn(turns.shift())
  } else if (message.ready && resendTurn) {
    // The stream recovered after an upstream_reset that cut this turn off: speak it again.
    resendTurn = false
    sendTurn(currentTurn)
  } else if (message.done) {
    if (turns.length > 0) sendTurn(turns.shift())
    else ws.send(JSON.stringify({ eos: true }))
  } else if (message.error) {
    if (message.error === 'upstream_reset') resendTurn = message.turn_lost === true
    console.error('Stream error:', message)
  }
})

ws.on('close', (code, reason) => {
  audio.end()
  console.log(`Closed: ${code} ${reason}`)
})

Play the result with SoX:

play -t raw -r 24000 -e signed -b 16 -c 1 output.pcm