> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tryhamsa.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Text-to-Speech

> Convert text to streaming audio via WebSocket

<Note>
  Connect to the WebSocket and send TTS requests to convert text into streaming audio.
</Note>

## Quick Start

1. Enter your API key in the authentication field
2. Click **Connect** to establish the WebSocket connection
3. Modify the request payload with your text
4. Click **Send** to receive streaming audio

## Request Message

After connecting, send a JSON message with the following structure:

<ParamField body="type" type="string" required>
  Must be `"tts"`
</ParamField>

<ParamField body="payload" type="object" required>
  <Expandable title="payload properties">
    <ParamField body="text" type="string" required>
      The text to synthesize. Maximum 2000 characters.
    </ParamField>

    <ParamField body="speaker" type="string" required>
      Voice name (e.g. `Amjad`) or the UUID of a custom cloned voice. Pick a speaker that matches the chosen dialect — see the dialect field below for voice examples.
    </ParamField>

    <ParamField body="dialect" type="string" required>
      Dialect to synthesize. One of: `pls`, `egy`, `syr`, `irq`, `jor`, `leb`, `ksa`, `uae`, `bah`, `qat`, `kuw`, `oma`, `msa`, `ar-sa`, `en`. See [Dialects and Voice Examples](#dialects-and-voice-examples) below.
    </ParamField>

    <ParamField body="languageId" type="string" required example="ar">
      Language code. (e.g., "ar").
    </ParamField>

    <ParamField body="mulaw" type="boolean" required example="false">
      Whether to use mu-law audio encoding. (e.g., false)
    </ParamField>

    <ParamField body="expressiveness" type="number" default="1">
      Controls how expressive the generated speech sounds, from `0` (flat and monotone) to `2` (highly expressive). Defaults to `1`.
    </ParamField>
  </Expandable>
</ParamField>

```json TTS Request theme={null}
{
  "type": "tts",
  "payload": {
    "text": "مرحبا بك في خدمة همسة",
    "speaker": "Amjad",
    "dialect": "pls",
    "languageId": "ar",
    "mulaw": false,
    "expressiveness": 1
  }
}
```

## Response Sequence

The server responds with:

```json 1. Acknowledgment theme={null}
{
  "type": "ack",
  "payload": {
    "message": "Real time text to speach connection establesh"
  }
}
```

```json 2. Binary Audio Chunks theme={null}
// Raw binary audio data streamed in chunks
// Buffer these chunks to reconstruct the complete audio
```

```json 3. Stream End theme={null}
{
  "type": "end",
  "payload": {
    "message": "End of TTS stream"
  }
}
```

## Dialects and Voice Examples

Pick a `speaker` that matches your chosen `dialect`. Voice examples per dialect:

| Dialect       | Code    | Voice examples |
| ------------- | ------- | -------------- |
| Palestinian   | `pls`   | Amjad, Layan   |
| Egyptian      | `egy`   | Mariam, Samir  |
| Syrian        | `syr`   | Dalal, Mais    |
| Iraqi         | `irq`   | Lyali, Fatma   |
| Jordanian     | `jor`   | Lana, Jasem    |
| Lebanese      | `leb`   | Carla, Majd    |
| Saudi         | `ksa`   | Hiba, Fahd     |
| Emirati       | `uae`   | Salma, Dima    |
| Bahraini      | `bah`   | Mazen, Ruba    |
| Qatari        | `qat`   | Deema, Faisal  |
| Kuwaiti       | `kuw`   | Mai, Hatem     |
| Omani         | `oma`   | Aisha, Jaber   |
| MSA / Fusha   | `msa`   | Salem, Tamim   |
| Arabic – Gulf | `ar-sa` | Khalid, Rahma  |
| English       | `en`    | Emma, James    |

## Available Speakers

Refer to Hamsa Platforms to get the list of the available pre-built speakers where you can take the name of the speaker, or use a UUID for your custom cloned voice.

## Using Custom Cloned Voices

When using a custom cloned voice (UUID) as the speaker, you must preload the voice before establishing the WebSocket connection. This ensures optimal latency during streaming.

<Warning>
  **Preload Required for Custom Voices**

  Call the [Preload Voice endpoint](/developers/apis/use-cloned-voice-id-as-speaker) once when your application starts to avoid latency when using custom cloned voices.
</Warning>

```javascript theme={null}
// 1. Preload the custom voice at app startup
await fetch('https://api.tryhamsa.com/v2/tts/voices/custom/preload', {
  method: 'POST',
  headers: {
    'Authorization': 'Token YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ voiceId: 'your-custom-voice-uuid' })
});

// 2. Now connect to WebSocket and use the custom voice
const ws = new WebSocket('wss://api.tryhamsa.com/v1/realtime/ws?api_key=YOUR_API_KEY');

ws.onopen = () => {
  ws.send(JSON.stringify({
    type: 'tts',
    payload: {
      text: 'Hello from my custom voice',
      speaker: 'your-custom-voice-uuid', // Use the same UUID
      dialect: 'pls',
      languageId: 'ar',
      mulaw: false
    }
  }));
};
```


## AsyncAPI

````yaml websocket/asyncapi-tts.json tts
id: tts
title: Text-to-Speech
description: Convert text to speech with streaming audio output
servers:
  - id: production
    protocol: wss
    host: api.tryhamsa.com/v1/realtime/ws
    bindings: []
    variables: []
address: /
parameters: []
bindings: []
operations:
  - &ref_1
    id: sendTTSRequest
    title: Send TTS Request
    description: Send a text-to-speech request to convert text into streaming audio
    type: receive
    messages:
      - &ref_3
        id: ttsRequest
        contentType: application/json
        payload:
          - name: TTS Request
            description: Request to convert text to speech
            type: object
            properties:
              - name: type
                type: string
                description: Message type identifier
                required: true
              - name: payload
                type: object
                required: true
                properties:
                  - name: text
                    type: string
                    description: >-
                      The text to synthesize into speech. Maximum 2000
                      characters.
                    required: true
                  - name: speaker
                    type: string
                    description: >-
                      Voice name (e.g. 'Amjad') or the UUID of a custom cloned
                      voice. Pick a speaker that matches the chosen dialect.
                    required: true
                  - name: dialect
                    type: string
                    description: >-
                      Dialect to synthesize. Voice examples per dialect: pls
                      (Palestinian) — Amjad, Layan; egy (Egyptian) — Mariam,
                      Samir; syr (Syrian) — Dalal, Mais; irq (Iraqi) — Lyali,
                      Fatma; jor (Jordanian) — Lana, Jasem; leb (Lebanese) —
                      Carla, Majd; ksa (Saudi) — Hiba, Fahd; uae (Emirati) —
                      Salma, Dima; bah (Bahraini) — Mazen, Ruba; qat (Qatari) —
                      Deema, Faisal; kuw (Kuwaiti) — Mai, Hatem; oma (Omani) —
                      Aisha, Jaber; msa (MSA / Fusha) — Salem, Tamim; ar-sa
                      (Arabic – Gulf) — Khalid, Rahma; en (English) — Emma,
                      James.
                    enumValues:
                      - pls
                      - egy
                      - syr
                      - irq
                      - jor
                      - leb
                      - ksa
                      - uae
                      - bah
                      - qat
                      - kuw
                      - oma
                      - msa
                      - ar-sa
                      - en
                    required: false
                  - name: languageId
                    type: string
                    description: Language code. Defaults to 'ar' (Arabic).
                    required: false
                  - name: mulaw
                    type: boolean
                    description: Whether to use mu-law audio encoding.
                    required: false
                  - name: expressiveness
                    type: number
                    description: >-
                      Controls how expressive the generated speech sounds. 0 is
                      flat and monotone, 1 is the natural default, and 2 is
                      highly expressive.
                    required: false
        headers: []
        jsonPayloadSchema:
          type: object
          required:
            - type
            - payload
            - dialect
            - languageId
            - mulaw
          properties:
            type:
              type: string
              const: tts
              description: Message type identifier
              x-parser-schema-id: <anonymous-schema-1>
            payload:
              type: object
              required:
                - text
                - speaker
              properties:
                text:
                  type: string
                  minLength: 1
                  maxLength: 2000
                  description: The text to synthesize into speech. Maximum 2000 characters.
                  x-parser-schema-id: <anonymous-schema-3>
                speaker:
                  type: string
                  minLength: 1
                  description: >-
                    Voice name (e.g. 'Amjad') or the UUID of a custom cloned
                    voice. Pick a speaker that matches the chosen dialect.
                  x-parser-schema-id: <anonymous-schema-4>
                dialect:
                  type: string
                  enum:
                    - pls
                    - egy
                    - syr
                    - irq
                    - jor
                    - leb
                    - ksa
                    - uae
                    - bah
                    - qat
                    - kuw
                    - oma
                    - msa
                    - ar-sa
                    - en
                  description: >-
                    Dialect to synthesize. Voice examples per dialect: pls
                    (Palestinian) — Amjad, Layan; egy (Egyptian) — Mariam,
                    Samir; syr (Syrian) — Dalal, Mais; irq (Iraqi) — Lyali,
                    Fatma; jor (Jordanian) — Lana, Jasem; leb (Lebanese) —
                    Carla, Majd; ksa (Saudi) — Hiba, Fahd; uae (Emirati) —
                    Salma, Dima; bah (Bahraini) — Mazen, Ruba; qat (Qatari) —
                    Deema, Faisal; kuw (Kuwaiti) — Mai, Hatem; oma (Omani) —
                    Aisha, Jaber; msa (MSA / Fusha) — Salem, Tamim; ar-sa
                    (Arabic – Gulf) — Khalid, Rahma; en (English) — Emma, James.
                  x-parser-schema-id: <anonymous-schema-5>
                languageId:
                  type: string
                  default: ar
                  description: Language code. Defaults to 'ar' (Arabic).
                  x-parser-schema-id: <anonymous-schema-6>
                mulaw:
                  type: boolean
                  default: false
                  description: Whether to use mu-law audio encoding.
                  x-parser-schema-id: <anonymous-schema-7>
                expressiveness:
                  type: number
                  minimum: 0
                  maximum: 2
                  default: 1
                  description: >-
                    Controls how expressive the generated speech sounds. 0 is
                    flat and monotone, 1 is the natural default, and 2 is highly
                    expressive.
                  x-parser-schema-id: <anonymous-schema-8>
              x-parser-schema-id: <anonymous-schema-2>
          x-parser-schema-id: TTSRequestPayload
        title: TTS Request
        description: Request to convert text to speech
        example: |-
          {
            "type": "tts",
            "payload": {
              "text": "مرحبا بك في خدمة همسة",
              "speaker": "Amjad",
              "dialect": "pls",
              "languageId": "ar",
              "mulaw": false,
              "expressiveness": 1
            }
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: ttsRequest
    bindings: []
    extensions: &ref_0
      - id: x-parser-unique-object-id
        value: tts
  - &ref_2
    id: receiveTTSResponse
    title: Receive TTS Response
    description: Receive acknowledgment, audio chunks, and end signal
    type: send
    messages:
      - &ref_4
        id: ttsAck
        contentType: application/json
        payload:
          - name: TTS Acknowledgment
            description: Server acknowledges the TTS request
            type: object
            properties:
              - name: type
                type: string
                description: ack
                required: false
              - name: payload
                type: object
                required: false
                properties:
                  - name: message
                    type: string
                    required: false
        headers: []
        jsonPayloadSchema:
          type: object
          properties:
            type:
              type: string
              const: ack
              x-parser-schema-id: <anonymous-schema-9>
            payload:
              type: object
              properties:
                message:
                  type: string
                  x-parser-schema-id: <anonymous-schema-11>
              x-parser-schema-id: <anonymous-schema-10>
          x-parser-schema-id: AckPayload
        title: TTS Acknowledgment
        description: Server acknowledges the TTS request
        example: |-
          {
            "type": "ack",
            "payload": {
              "message": "Real time text to speach connection establesh"
            }
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: ttsAck
      - &ref_5
        id: ttsAudioChunk
        contentType: application/octet-stream
        payload:
          - type: string
            format: binary
            description: Binary audio data chunk
            x-parser-schema-id: <anonymous-schema-12>
            name: TTS Audio Chunk
        headers: []
        jsonPayloadSchema:
          type: string
          format: binary
          description: >-
            Raw audio bytes. Buffer multiple chunks to reconstruct the complete
            audio file.
          x-parser-schema-id: <anonymous-schema-12>
        title: TTS Audio Chunk
        description: Binary audio data chunk
        example: '{}'
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: ttsAudioChunk
      - &ref_6
        id: ttsEnd
        contentType: application/json
        payload:
          - name: TTS Stream End
            description: Signals the end of the audio stream
            type: object
            properties:
              - name: type
                type: string
                description: end
                required: false
              - name: payload
                type: object
                required: false
                properties:
                  - name: message
                    type: string
                    required: false
        headers: []
        jsonPayloadSchema:
          type: object
          properties:
            type:
              type: string
              const: end
              x-parser-schema-id: <anonymous-schema-13>
            payload:
              type: object
              properties:
                message:
                  type: string
                  x-parser-schema-id: <anonymous-schema-15>
              x-parser-schema-id: <anonymous-schema-14>
          x-parser-schema-id: EndPayload
        title: TTS Stream End
        description: Signals the end of the audio stream
        example: |-
          {
            "type": "end",
            "payload": {
              "message": "End of TTS stream"
            }
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: ttsEnd
      - &ref_7
        id: errorResponse
        contentType: application/json
        payload:
          - name: Error Response
            description: Error message from the server
            type: object
            properties:
              - name: type
                type: string
                description: error
                required: false
              - name: payload
                type: object
                required: false
                properties:
                  - name: message
                    type: string
                    description: Error description
                    required: false
        headers: []
        jsonPayloadSchema:
          type: object
          properties:
            type:
              type: string
              const: error
              x-parser-schema-id: <anonymous-schema-16>
            payload:
              type: object
              properties:
                message:
                  type: string
                  description: Error description
                  x-parser-schema-id: <anonymous-schema-18>
              x-parser-schema-id: <anonymous-schema-17>
          x-parser-schema-id: ErrorPayload
        title: Error Response
        description: Error message from the server
        example: |-
          {
            "type": "error",
            "payload": {
              "message": "Invalid payload for message type: tts"
            }
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: errorResponse
    bindings: []
    extensions: *ref_0
sendOperations:
  - *ref_1
receiveOperations:
  - *ref_2
sendMessages:
  - *ref_3
receiveMessages:
  - *ref_4
  - *ref_5
  - *ref_6
  - *ref_7
extensions:
  - id: x-parser-unique-object-id
    value: tts
securitySchemes:
  - id: apiKey
    name: api_key
    type: httpApiKey
    description: API key passed as query parameter or X-Api-Key header
    in: query
    extensions: []

````