# Speak SSML documents

POST /v1/tts and the live sockets speak an SSML document on Paxa TTS Flash v2: SSML 1.1 with Azure's mstts extensions, with voices, breaks, prosody, styles, marks, audio clips, and background audio. What reads, what is ignored, the limits, and a migration map from Azure.

Send an SSML document as `ssml` in place of `text` to [POST /v1/tts](https://paxalabs.com/docs/api/text-to-speech), or as an `ssml` frame on a [live socket](#live), and Paxa TTS Flash v2 speaks it. It reads SSML 1.1 with the `mstts` extensions of Azure AI Speech: voices, breaks, prosody, emphasis, styles, silences, marks, audio clips, and background audio. Each element compiles to the model's own [direction tags](https://paxalabs.com/docs/directions) and [pauses](https://paxalabs.com/docs/pauses), to silence, or to audio. The API checks the document and fetches its audio before any charge. A document written for Azure reads once its voice names are Paxa voice ids, and [Migrate from Azure](#azure) lists every other difference.

SSML:

```xml
<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="http://www.w3.org/2001/mstts" xml:lang="th">
  <voice name="khanomkrok">
    <mstts:express-as style="customerservice">สวัสดีครับ ขอบคุณที่โทรหา Paxa Labs</mstts:express-as>
    <break time="300ms"/>
    <prosody rate="-10%">กรุณาถือสายรอสักครู่ เจ้าหน้าที่จะรับสายโดยเร็วที่สุดครับ</prosody>
    <mark name="hold"/>
    <break time="2s"/>
    หากต้องการฟังเมนูอีกครั้ง กด <emphasis>9</emphasis> ครับ
  </voice>
</speak>
```

curl:

```bash
curl -X POST https://api.paxalabs.com/v1/tts \
  -H "Authorization: Bearer $PAXA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "ssml": "<speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" xmlns:mstts=\"http://www.w3.org/2001/mstts\" xml:lang=\"th\">\n  <voice name=\"khanomkrok\">\n    <mstts:express-as style=\"customerservice\">สวัสดีครับ ขอบคุณที่โทรหา Paxa Labs</mstts:express-as>\n    <break time=\"300ms\"/>\n    <prosody rate=\"-10%\">กรุณาถือสายรอสักครู่ เจ้าหน้าที่จะรับสายโดยเร็วที่สุดครับ</prosody>\n    <mark name=\"hold\"/>\n    <break time=\"2s\"/>\n    หากต้องการฟังเมนูอีกครั้ง กด <emphasis>9</emphasis> ครับ\n  </voice>\n</speak>",
  "voice": "khanomkrok",
  "model": "paxa-tts-flash-v2"
}' \
  --output speech.mp3 \
  --dump-header headers.txt
```

TypeScript:

```typescript
import { writeFile } from "node:fs/promises";

const response = await fetch("https://api.paxalabs.com/v1/tts", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.PAXA_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "ssml": "<speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" xmlns:mstts=\"http://www.w3.org/2001/mstts\" xml:lang=\"th\">\n  <voice name=\"khanomkrok\">\n    <mstts:express-as style=\"customerservice\">สวัสดีครับ ขอบคุณที่โทรหา Paxa Labs</mstts:express-as>\n    <break time=\"300ms\"/>\n    <prosody rate=\"-10%\">กรุณาถือสายรอสักครู่ เจ้าหน้าที่จะรับสายโดยเร็วที่สุดครับ</prosody>\n    <mark name=\"hold\"/>\n    <break time=\"2s\"/>\n    หากต้องการฟังเมนูอีกครั้ง กด <emphasis>9</emphasis> ครับ\n  </voice>\n</speak>",
    "voice": "khanomkrok",
    "model": "paxa-tts-flash-v2"
  }),
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile("speech.mp3", Buffer.from(await response.arrayBuffer()));
console.log(JSON.parse(response.headers.get("x-ssml-marks")!).marks);
console.log(JSON.parse(response.headers.get("x-ssml-report")!).notes);
```

Python:

```python
import json
import os
import requests

response = requests.post(
    "https://api.paxalabs.com/v1/tts",
    headers={"Authorization": f"Bearer {os.environ['PAXA_API_KEY']}"},
    json={
        "ssml": "<speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" xmlns:mstts=\"http://www.w3.org/2001/mstts\" xml:lang=\"th\">\n  <voice name=\"khanomkrok\">\n    <mstts:express-as style=\"customerservice\">สวัสดีครับ ขอบคุณที่โทรหา Paxa Labs</mstts:express-as>\n    <break time=\"300ms\"/>\n    <prosody rate=\"-10%\">กรุณาถือสายรอสักครู่ เจ้าหน้าที่จะรับสายโดยเร็วที่สุดครับ</prosody>\n    <mark name=\"hold\"/>\n    <break time=\"2s\"/>\n    หากต้องการฟังเมนูอีกครั้ง กด <emphasis>9</emphasis> ครับ\n  </voice>\n</speak>",
        "voice": "khanomkrok",
        "model": "paxa-tts-flash-v2",
    },
)
response.raise_for_status()
with open("speech.mp3", "wb") as f:
    f.write(response.content)
print(json.loads(response.headers["x-ssml-marks"])["marks"])
print(json.loads(response.headers["x-ssml-report"])["notes"])
```

The response is the audio file, as for `text`. Its `x-ssml-report` header lists what the API did not read as written, and `x-ssml-marks` gives the time of each mark, here `hold`.

## Send a request

The body carries the document in `ssml` in place of `text`, and a body with both answers [400 validation](https://paxalabs.com/docs/errors#validation) at `body.ssml`. Only `paxa-tts-flash-v2` reads SSML, and another model answers 400 validation at `body.model` with `not_allowed`. The other fields read as for `text`, with these differences:

- `voice`, still required, speaks the text outside every `voice` element, and must name a voice even when every element names its own.
- `format`, `sample_rate`, `stream`, `speed`, and `temperature` read as for `text`. Clips and the background play in the response's format and rate.
- `timestamps` takes `word` alone and times every word, measured from the start of the output. Another value answers 400 validation at `body.timestamps` with `not_allowed`.
- `language` sets how codes, digits, and symbols are read. At `auto`, the default, the `xml:lang` of `speak` sets it when it names `th`, `en`, `zh`, with or without a region as in `th-TH`. Another `xml:lang` is noted `ignored`.

## What each element does

Elements with no namespace or in the SSML namespace read as this table lists. So do elements in the `mstts` namespace, declared as `http://www.w3.org/2001/mstts` or its `https` form, or written on an undeclared `mstts` prefix.

| Element | Reads | What it does |
| --- | --- | --- |
| `speak` | `version`, `xml:lang`, `startmark`, `endmark` | The root. `xml:lang` sets the reading language when `language` is `auto`, and `startmark` and `endmark` speak only what lies between those marks. |
| `voice` | `name` | Speaks its text in the voice it names (see [Voices](#voices)). A change of voice starts a new speech item. |
| `p`, `s` | None | Separate the paragraphs and sentences of the text. |
| `break` | `time`, `strength` | Silence where it stands, and breaks in a row add up. Between words of one voice, up to 500 ms is an exact [pause tag](https://paxalabs.com/docs/pauses#exact) in the text, rounded to 10 ms. A longer break, or one beside a clip, a change of voice, or either end, is silence between speech items. `time` plays up to 20,000 ms, and with neither attribute a break is `medium`. |
| `prosody` | `rate`, `pitch`, `range`, `volume` | Changes the rate, pitch, pitch range, and loudness of its text with setting tags, reset where it ends (see [Prosody](#prosody)). `volume="silent"` leaves its text unspoken. |
| `emphasis` | `level` | `moderate`, the default, writes `<emph:0.5>`, and `strong` writes `<emph>`. `none` lifts an emphasis in force, and `reduced` is ignored. |
| `sub` | `alias` | Speaks `alias` in place of its content. |
| `mark`, `mstts:bookmark` | `name`, `mark` | Places a mark the response times (see [Marks](#marks)). |
| `mstts:express-as` | `style`, `styledegree` | Plays its text in the direction its style maps to (see [Styles](#styles)) and returns to the delivery around it where it ends. |
| `mstts:silence` | `type`, `value` | Sets silence for the element that holds it (see [Silence types](#silence)). |
| `audio` | `src`, `clipBegin`, `clipEnd`, `repeatCount`, `repeatDur`, `soundLevel`, `speed`, `fetchtimeout` | Plays a recording, or reads its content when the recording does not play (see [Audio clips](#audio)). |
| `mstts:backgroundaudio` | `src`, `volume`, `fadein`, `fadeout` | Lays a recording under the whole output (see [Background audio](#background)). |

Every element reads `xml:base`, which resolves a relative audio `src`. Text reads as `text` does on POST /v1/tts: runs of whitespace read as one space, and bracket tags such as `[laughs]` or `[pause 300ms]` read as written and are checked before any charge. Write `<emph>` and `<whisper>` escaped, as `&lt;whisper&gt;` and `&lt;/whisper&gt;`, since unescaped they are elements. Where silence, a clip, or another voice parts a voice's speech, the next speech item in that voice opens with the tags of your text still in force.

### Break strengths

| strength | Silence |
| --- | --- |
| none | 0 ms |
| x-weak | 250 ms |
| weak | 500 ms |
| medium | 750 ms |
| strong | 1000 ms |
| x-strong | 1250 ms |

### Prosody

- `rate` takes a keyword as a factor of the voice's rate (`x-slow` 0.5, `slow` 0.64, `medium` 1, `default` 1, `fast` 1.55, `x-fast` 2), a percentage that changes the rate in force, or a factor (`1.2`). A percentage reads as Azure reads it: `20%` and `+20%` both play 1.2 times as fast. W3C SSML reads an unsigned percentage as a share of the voice's rate instead. It plays from 0.5 to 1.5 times the voice's rate.
- `pitch` takes a keyword as a factor of the voice's pitch (`x-low` 0.55, `low` 0.8, `medium` 1, `default` 1, `high` 1.2, `x-high` 1.45), or semitones (`+2st`) or a percentage (`-10%`) that change the pitch in force. It plays within 6 semitones of the voice's own, and a pitch in Hz is ignored.
- `range` takes the pitch keywords as factors of the voice's range, or a percentage that changes it. It plays from 0.5 to 1.5 times the voice's range, and a range in semitones or Hz is ignored.
- `volume` takes a keyword on Azure's 0 to 100 scale, where 100 is the voice's own level (`silent` 0, `x-soft` 20, `soft` 40, `medium` 60, `loud` 80, `x-loud` 100, `default` 100), or a number on that scale. A signed number (`+10`), decibels (`+3dB`), or a percentage, signed or not (`-20%`, `50%`), changes the level in force. It plays within 6 dB of the voice's own level, and a level of 0 leaves the text unspoken.

A value outside its band plays at the nearer end and is noted `clamped`. A form the model cannot play is noted `ignored`, and a value that does not parse `unreadable`.

## Voices

A `voice` element names its voice in `name`. The name is a voice id from [GET /v1/voices](https://paxalabs.com/docs/api/voices), in any case, or a [designed voice](https://paxalabs.com/docs/designed-voices) id, which speaks only for its own account. The element reads no other attribute. No voice is chosen by gender or language, and Azure voice names do not map to Paxa voices. Text outside every voice element speaks the request's `voice`.

A name the API does not serve answers [400 unknown_voice](https://paxalabs.com/docs/errors#unknown_voice) with `path` naming the voice element, and a voice element without a name answers 400 ssml_invalid with `voice_name_required`. Every Paxa TTS Flash v2 voice speaks English, Thai, and Mandarin. A change of language needs no change of voice.

## Marks

`<mark name="..."/>` and `<mstts:bookmark mark="..."/>` place marks, up to 200 in a document and each name up to 64 characters. The response gives every mark in document order with its `time`, in seconds from the start of the output, rounded to the millisecond. A mark falls at the start of the word after it. With no word after it in its speech item, as before a break, a clip, or a change of voice, it falls at the end of the speech before it. A mark after a break falls at the start of what plays next, and a mark at the end of the document at the end of the output. Marks never change the charge.

- A buffered audio response carries them in `x-ssml-marks`, as `{"marks":[{"name","time"}]}`.
- A response with `timestamps` carries them in its `marks` array.
- A streamed request whose document holds a mark answers NDJSON. `chunk` events carry the audio, and `done` ends the stream. A `mark` event arrives once the speech item or clip it falls in has been sent, up to one item after its audio.

NDJSON stream:

```json
{"type":"chunk","audio":"SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYy..."}
{"type":"chunk","audio":"//NkxAAaOAAAAAABLBQAAAAAAABVVVVV..."}
{"type":"mark","name":"hold","time":6.412}
{"type":"chunk","audio":"//NkxAAaOAAAAAABLBQAAAAAAABVVVVV..."}
{"type":"done"}
```

Set `startmark` or `endmark` on `speak` to speak only the part of the document after the first mark or before the second. A name the document lacks answers ssml_invalid with `mark_not_found`. A mark inside an `audio` element counts only when that element's content reads. An `endmark` there ends the output only when the clip does not play. A `startmark` there is never reached.

## Read the report

Every success carries `x-ssml-report`, JSON that lists what the API did not read as written: `{"notes":[{"path","code","reason"}]}`, one note per element or attribute in document order. `path` names an element as `/speak/voice[1]/prosody[2]` and an attribute as `/speak/voice[1]/prosody[2]/@rate`. `reason` appears on a `fallback` note and on the `ignored` note of a background that did not play. A header that would pass 6,144 bytes ends its list with `"truncated":true`, characters past ASCII are written as `\u` escapes, and `x-ssml-marks` follows the same rules. A document whose `say-as` was ignored and whose clip could not be fetched reports this:

Response headers:

```http
x-ssml-report: {"notes":[{"path":"/speak/voice[1]/say-as[1]","code":"ignored"},{"path":"/speak/voice[1]/audio[1]","code":"fallback","reason":"fetch_failed"}]}
x-ssml-marks: {"marks":[{"name":"hold","time":6.412}]}
```

| code | Meaning |
| --- | --- |
| ignored | The element's markup or the attribute was ignored. An element's content is still read, except in meta, metadata, lexicon, desc, and math. |
| unreadable | The attribute was ignored. Its value could not be read. |
| clamped | The value was held to the nearest end of the range the model plays. |
| fallback | The audio did not play, and the element's content was read in its place. reason says why. |

`say-as`, `phoneme`, `lexicon`, `lookup`, `lang`, `token`, `w`, and a nested `speak` are ignored with a note. So is any other element outside the table above, other `mstts` elements included. Their content reads as plain text, except that `math` and `lexicon` content is skipped. `meta`, `metadata`, and `desc` are skipped without a note. An attribute an element does not read is noted at its own path, except namespace declarations, `xml:space`, `xml:id`, and `xml:base`.

## Play audio clips

An `audio` element plays a recording between speech items. Its `src` is an `https`, `http`, or `data:` URL, and a relative `src` resolves against the nearest `xml:base`. When the recording does not play, the element's content reads in its place, its `desc` children skipped, and the report carries a `fallback` note whose `reason` says why. An `audio` element inside that content plays only when its parent does not.

SSML:

```xml
<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="http://www.w3.org/2001/mstts" xml:lang="th">
  <mstts:backgroundaudio src="https://example.com/audio/hold-music.mp3" volume="0.3" fadein="2000" fadeout="1500"/>
  <voice name="khanomkrok">
    <audio src="https://example.com/audio/welcome.wav" soundLevel="-3dB">
      <desc>The recorded welcome prompt</desc>
      ยินดีต้อนรับสู่ศูนย์บริการลูกค้าครับ
    </audio>
    <break time="1s"/>
    เจ้าหน้าที่ของเราจะรับสายในอีกไม่กี่นาทีครับ
  </voice>
</speak>
```

- `clipBegin` and `clipEnd` trim the file, as times such as `1.5s` or `800ms`, and `clipEnd` must fall after `clipBegin`.
- `repeatCount` plays the clip that many times, over 0 and up to 100, and a fraction ends partway.
- `repeatDur` caps the played length, repeats included.
- `soundLevel` changes the clip's level in decibels, from `-96dB` to `+12dB`.
- `speed` plays the clip at a percentage of its rate, from `50%` to `200%`, and its pitch moves with it.
- `fetchtimeout` limits the fetch, from 1,000 to 15,000 ms, 10,000 ms by default.

A value outside its range plays at the nearer end and is noted `clamped`.

### How a clip is fetched

- A URL whose scheme is not `https`, `http`, or `data:` is `blocked`. A `data:` URL is base64 or percent-encoded.
- These hosts are `blocked` before any request: `localhost`, single-label names, names ending `.internal`, `.local`, or `.localhost`, and `paxalabs.com` with every name under it.
- A port other than 80, 443, or 1024 to 65535 is `blocked`.
- Addresses in private, shared, loopback, link-local, multicast, reserved, and documentation ranges are never connected to, IPv4 and IPv6 alike, and an IPv4 address written inside IPv6 counts as that address. A host with no address left is `blocked`.
- A fetch follows up to 5 redirects, each checked by the same rules, and sends no cookies and no referrer.
- A server answer other than 2xx is `fetch_failed`, a fetch past its `fetchtimeout` is `timeout`, and a file over 20 MiB, after a `data:` URL's decoding, is `too_large`. Every fetch of a request ends within 20 seconds.
- A response that states its freshness with `Cache-Control: max-age` or `Expires` can serve your account's later requests for the same URL for that long, a day at most. `no-store` and `no-cache` are honored, and a `data:` URL is read each time.

### Supported audio

- The bytes decide the format. MP3, AIFF, FLAC, Ogg Vorbis, Ogg Opus, and AAC or ALAC in MP4 decode. WAV decodes as 8, 16, 24, or 32-bit integer, 32 or 64-bit float, IMA or MS ADPCM, A-law, or mu-law.
- Raw G.711 at 8 kHz, marked by its media type: `audio/basic`, `audio/x-mulaw`, or `audio/pcmu` as mu-law, and `audio/x-alaw-basic` or `audio/pcma` as A-law.
- Rates from 8 to 192 kHz and up to 8 channels, mixed to mono. Any other format, WMA included, is `unsupported`.
- A file longer than 600 seconds is `too_long`. The clips of one request play 600 seconds at most, repeats included, counted in document order, and a clip that would pass what is left is `too_long` and its content reads.

| reason | Meaning |
| --- | --- |
| blocked | The URL's scheme, host, port, or address is refused: a private or reserved address, a single-label or internal name, or a Paxa host. |
| fetch_failed | The file could not be fetched: the host was not found, the connection or TLS failed, or the server answered other than 2xx. |
| timeout | The fetch did not finish within its timeout. |
| too_large | The file is larger than 20 MiB. |
| too_long | The file is longer than 600 seconds, or playing it would pass the request's 600 seconds of clips. |
| unsupported | The file is not audio in a supported format, or holds none. |
| malformed | The data: URL has no comma, or its base64 is malformed. |
| no_src | The element has no src. |
| relative_src | src is relative and no xml:base resolves it. |
| unavailable | The audio service could not be reached. |

## Add background audio

`mstts:backgroundaudio` lays one recording under the whole output. Place it as a direct child of `speak`. Anywhere else it is ignored with a note, and a second one answers ssml_invalid with `background_repeated`. The recording loops from the start of the output. `fadein` fades it in over that many milliseconds. `fadeout` keeps it playing that long after the speech ends while it fades to silence. Each fade is up to 10,000 ms. `volume` is a linear gain from 0 to 1, 1 by default. A value over 1 reads as a percentage, and `30` plays as `0.3`. The background is fetched under the clip rules. When it does not play, the speech plays alone, and the report carries an `ignored` note with the `reason`.

## Refusals

A document the API cannot read answers [400 ssml_invalid](https://paxalabs.com/docs/errors#ssml_invalid) before any charge. The problem adds `reason`, `path`, the element at fault, and `line` and `column`, both counted from 1. For an element they point where its start tag closes. For a document that is not well-formed, they point at the character where reading stopped. Positions count from the document as sent, leading whitespace included, and a byte order mark takes no column. `mark_not_found` names the `startmark` or `endmark` attribute, and `too_many_lines` and `too_much_silence`, which count the compiled document, name `/speak`.

| reason | Meaning |
| --- | --- |
| malformed | The document is not well-formed XML: a tag left open, an attribute without quotes, an unknown entity, or a character XML forbids. |
| doctype | The document declares a DOCTYPE. Entity and DTD declarations are refused. Only the five XML entities and numeric character references read. |
| root_not_speak | The root element is not speak. |
| too_deep | Elements nest deeper than 32 levels. |
| too_many_elements | The document holds more than 5,000 elements. |
| too_many_attributes | An element carries more than 32 attributes. |
| attribute_too_long | An attribute other than an audio src holds more than 8,192 characters. |
| voice_name_required | A voice element has no name. The name alone selects the voice and takes a voice id from GET /v1/voices or a designed voice id. |
| mark_name_required | A mark has no name, or a bookmark has no mark. |
| mark_name_too_long | A mark name is longer than 64 characters. |
| too_many_marks | The document holds more than 200 marks. |
| mark_not_found | startmark or endmark names a mark the document lacks, or one only in content it never speaks, such as a sub with an alias. |
| too_many_audio | The document holds more than 50 audio elements, counting nested fallbacks and the background. |
| background_repeated | The document holds more than one mstts:backgroundaudio. |
| too_many_lines | The document compiles to more than 200 speech items and clips. A voice change, a clip, and a break longer than the longest exact pause each start a new one. |
| too_much_silence | The breaks and silences together exceed 600 seconds. |

These refusals also answer before any charge:

- [400 validation](https://paxalabs.com/docs/errors#validation) at `body.ssml` for a body that also sends `text`, at `body.model` with `not_allowed` for a model other than `paxa-tts-flash-v2`, and at `body.timestamps` with `not_allowed` for a granularity other than `word`.
- [400 unknown_voice](https://paxalabs.com/docs/errors#unknown_voice) with the voice element's `path`, or with no `path` when the request's `voice` is unknown.
- [400 tag_invalid](https://paxalabs.com/docs/errors#tag_invalid) for a bracket tag the model refuses, with the `path` of the element whose text holds it.
- [400 text_too_long](https://paxalabs.com/docs/errors#text_too_long) when the compiled text passes its ceiling (see [Limits](#limits)).
- [422 unspeakable_text](https://paxalabs.com/docs/errors#unspeakable_text) when the document has nothing to say: clips, silence, and tags alone.
- [503 provider_unavailable](https://paxalabs.com/docs/errors#provider_unavailable) when the document fetches audio while audio fetching is unavailable, or while the server cannot hold the request's clips. Neither case shows in [GET /health](https://paxalabs.com/docs/api/health). Retry it later.
- [429 concurrency_limited](https://paxalabs.com/docs/errors#concurrency_limited) when the account's documents in flight already hold as much clip audio as one account may. Retry once one of them ends.

## Billing

The text the document compiles to bills as `text` does on POST /v1/tts, 10 credits per 1,000 characters, and the document's markup does not. The tags the compiler writes count as text: a style's direction, a prosody span's setting tags, an emphasis mark, and a silence inside a speech item, which is an exact pause tag. Silence between speech items, clips, and background audio never bill. Bracket tags in your text bill as written, and again where a speech item opens with them. A speech item in a [designed voice](https://paxalabs.com/docs/designed-voices) bills at 1.25 times the rate, `timestamps` bills the request at 1.25 times, and marks never change the charge.

The sample at the top compiles to these 2 speech items, 196 characters in all, and costs 1.96 credits. Its long break is the silence between them. Rounding and the minimum work as [Credits and billing](https://paxalabs.com/docs/credits) describes.

Compiled speech items:

```
[friendly, helpful]สวัสดีครับ ขอบคุณที่โทรหา Paxa Labs[pause 300ms] [pace:0.9][neutral]กรุณาถือสายรอสักครู่ เจ้าหน้าที่จะรับสายโดยเร็วที่สุดครับ
หากต้องการฟังเมนูอีกครั้ง กด <emph:0.5>9</emph> ครับ
```

A failure after the charge keeps the price of the speech items delivered whole and refunds the rest. A failure before any audio is refunded whole and answers a problem whose `path` names the element where the failed speech item begins. An NDJSON stream ends with an `error` event whose `error.path` names that element and whose `credits` states what the request keeps, and a raw stream ends early.

## Limits

| Limit | Value |
| --- | --- |
| Document | 4,000,000 characters |
| Compiled text | 5,000 characters buffered, 20,000 streamed |
| Nesting | 32 levels |
| Elements | 5,000 |
| Attributes per element | 32 |
| One attribute | 8,192 characters; an audio `src` only by the document's length |
| Speech items and clips | 200 |
| Audio elements | 50, nested fallbacks and the background included |
| Marks | 200, each name up to 64 characters |
| One break or silence | 20 seconds; a longer value plays at it |
| Silence in all | 600 seconds |
| Clip playback in all | 600 seconds, repeats included |
| Repeats of one clip | 100 |
| One fetch | 1,000 to 15,000 ms, 10,000 by default |
| Every fetch of a request | 20 seconds |
| One file | 20 MiB and 600 seconds |
| Background fades | 10,000 ms each |
| Each report header | 6,144 bytes |

## Formats and streaming

`format` and `sample_rate` take the values of [POST /v1/tts](https://paxalabs.com/docs/text-to-speech#request-options), and clips and the background are encoded into the same file. What the response carries depends on `stream` and `timestamps`:

| Request | Response |
| --- | --- |
| Default | The audio file, with `x-ssml-report` and `x-ssml-marks`. |
| `stream: true` | The audio in chunks as it is synthesized, with `x-ssml-report`. A document that holds a mark streams NDJSON events instead. |
| `timestamps: "word"` | JSON with the base64 `audio`, its `timing`, and the `marks`. |
| Both | NDJSON events: `chunk` carries audio and `spans`, `mark` each mark, and `done` ends the stream. |

Decode each NDJSON `chunk` and join the bytes in arrival order for one file. A streamed `wav` states its sizes as 0xFFFFFFFF. Read it to the end of the stream.

## Speak SSML on a live socket

On [WS /v1/tts/live](https://paxalabs.com/docs/api/live) and each context of [WS /v1/tts/multi](https://paxalabs.com/docs/api/tts-multi), an `ssml` frame speaks one document as a leg of its own, after the buffered text, which flushes first. The session must run Paxa TTS Flash v2 with `timestamps` set to `word` or unset, or the frame answers `validation`. The session's voice speaks the text outside every `voice` element, and its format, speed, temperature, and language apply.

SSML:

```typescript
socket.onopen = () => {
  socket.send(JSON.stringify({
    type: "start",
    model: "paxa-tts-flash-v2",
    voice: "khanomkrok",
    timestamps: "word",
  }));
  // A document speaks as a leg of its own, after any buffered text.
  socket.send(JSON.stringify({
    type: "ssml",
    ssml: "<speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" xml:lang=\"th\">สวัสดีครับ<break time=\"300ms\"/><prosody rate=\"-10%\">กรุณาถือสายรอสักครู่</prosody><mark name=\"hold\"/></speak>",
  }));
  socket.send(JSON.stringify({ type: "end" }));
};

socket.onmessage = (event) => {
  if (typeof event.data !== "string") {
    player.feed(new Uint8Array(event.data));
    return;
  }
  const message = JSON.parse(event.data);
  // What did not read as written, before the leg's audio.
  if (message.type === "report") console.log(message.notes);
  // Seconds from the start of the leg's audio.
  if (message.type === "mark") console.log(message.name, message.time);
  // A refused document plays nothing; path names the element at fault.
  if (message.type === "error") console.error(message.code, message.path);
  if (message.type === "done") socket.close();
};
```

- The leg sends `charged`, then `report` with the notes `x-ssml-report` would carry, then its audio with `timing` and `mark` events, then `flushed`. A mark's `time` counts from the start of the leg's audio.
- The compiled text holds at most 20,000 characters, and the frame at most 64 KiB.
- A document refused before its charge plays nothing and is dropped; send it again once fixed. `ssml_invalid` carries `path`, `reason`, `line`, and `column`, and an error one element caused carries `path`.
- The leg bills into the connection's total, each speech item at its voice's rate. A leg that fails is refunded whole.

## Migrate from Azure

A document written for Azure AI Speech uses the same SSML 1.1 base and the same `mstts` namespace, and most of it reads unchanged. Change these before you send it:

- Send the document as `ssml` in a JSON body to `POST /v1/tts`, with `"model": "paxa-tts-flash-v2"` and your Paxa API key as a bearer token. Add a `voice` for the text outside every voice element, and choose the output with `format` and `sample_rate`.
- Replace each voice `name` with a voice id from GET /v1/voices or a designed voice id. Azure voice names do not map, and an unknown name answers 400 unknown_voice with the voice element's path.
- Write pronunciation into the text. `phoneme`, `lexicon`, and `say-as` are ignored, and their text reads as written. Spell out a date, an amount, or a code as it should be spoken, or give it a `sub` alias.
- Drop `lang` switches. Every Paxa TTS Flash v2 voice speaks English, Thai, and Mandarin, and `xml:lang` on `speak` or the `language` field sets how codes and digits read.
- Read marks from `x-ssml-marks`, the `marks` array, or `mark` events, and word timing from `timestamps: "word"`.
- Keep the compiled text within 5,000 characters buffered or 20,000 streamed. [Limits](#limits) lists the rest.

| Azure markup | Here |
| --- | --- |
| `speak`, `voice`, `p`, `s`, `sub`, `break` | Read as [What each element does](#elements) lists. Break strengths keep Azure's lengths. |
| `prosody` | `rate`, `pitch`, `range`, and `volume` read with Azure's keywords and percentages, held to the bands in [Prosody](#prosody). `contour` and a pitch in Hz are ignored. |
| `emphasis` | Read on every voice. |
| `mstts:express-as` | `style` and `styledegree` read through the [style map](#styles), and `role` is ignored. |
| `mstts:silence` | Read (see [Silence types](#silence)). |
| `bookmark` | A mark, as `mark` is. |
| `audio`, `mstts:backgroundaudio` | Read, with the fallback content of a clip that does not play. |
| `say-as`, `phoneme`, `lexicon`, `lang`, other `mstts` elements | Ignored, and their text reads as written. |

### Styles

Each Azure style plays as the direction below. `styledegree` weights it from 0.01 to 2, with 1 the default. `styledegree="2"` on `cheerful` writes `[cheerful:2]`. A style outside the list is ignored, and its text keeps the voice's own delivery.

| style | Direction |
| --- | --- |
| advertisement_upbeat | `[upbeat, high energy]` |
| affectionate | `[affectionate, warm]` |
| angry | `[angry]` |
| assistant | `[warm, relaxed]` |
| calm | `[calm, measured]` |
| chat | `[casual, relaxed]` |
| cheerful | `[cheerful]` |
| customerservice | `[friendly, helpful]` |
| depressed | `[despondent, low energy]` |
| disgruntled | `[disgruntled]` |
| documentary-narration | `[documentary narrator]` |
| embarrassed | `[embarrassed, hesitant]` |
| empathetic | `[empathetic, caring]` |
| envious | `[envious]` |
| excited | `[excited]` |
| fearful | `[fearful, nervous]` |
| friendly | `[friendly, warm]` |
| gentle | `[gentle, polite]` |
| hopeful | `[hopeful]` |
| lyrical | `[lyrical, sentimental]` |
| narration-professional | `[professional narrator]` |
| narration-relaxed | `[relaxed narrator, soothing]` |
| newscast | `[newsreader]` |
| newscast-casual | `[casual newsreader]` |
| newscast-formal | `[formal newsreader]` |
| poetry-reading | `[reading poetry]` |
| sad | `[sad]` |
| serious | `[serious, firm]` |
| shouting | `[calling out from a distance]` |
| sports_commentary | `[sports commentator]` |
| sports_commentary_excited | `[excited sports commentator]` |
| whispering | `<whisper>` |
| terrified | `[terrified]` |
| unfriendly | `[cold, indifferent]` |

### Silence types

`mstts:silence` sets silence for the element that holds it, and every `value` is a time of up to 20,000 ms. Leading, Tailing, and Sentenceboundary read the same with an `-exact` suffix.

| type | Silence |
| --- | --- |
| Leading | Before the element's content. |
| Tailing | After the element's content. |
| Sentenceboundary | Between the sentences inside it, after `.`, `!`, or `?` before a space, and after `。`, `！`, or `？`. |
| Comma-exact | After each `,` and `，`, up to 500 ms. |
| Semicolon-exact | After each `;` and `；`, up to 500 ms. |
| Enumerationcomma-exact | After each `、`, up to 500 ms. |

Punctuation followed by a digit, as in 1,000, takes no silence. A punctuation value over 500 ms plays at 500 ms and is noted `clamped`, and any other type is noted `unreadable`.
