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

# Text-To-Speech WebSocket

The Text-to-Speech WebSocket API is designed to generate audio from partial text input while ensuring consistency throughout the generated audio. Although highly flexible, the WebSocket API isn't a one-size-fits-all solution. It's well-suited for scenarios where:

* The input text is being streamed or generated in chunks.
* Real-time audio generation is required with low latency.
* You need to send text incrementally as it becomes available.

However, it may not be the best choice when:

* The entire input text is available upfront. Given that the generations are partial, some buffering is involved, which could potentially result in slightly higher latency compared to a standard HTTP request.
* You want to quickly experiment or prototype. Working with WebSockets can be harder and more complex than using a standard HTTP API, which might slow down rapid development and testing.

## Endpoint

```
WSS /websocket/text-to-speech
```

## Connection URL

```
wss://api.munsit.com/api/v1/websocket/text-to-speech?x-api-key=YOUR_API_KEY
```

## Authentication

Requires API key authentication via `x-api-key` query parameter or in the initial connection message.

## Query Parameters

| Parameter   | Type   | Required | Description         |
| ----------- | ------ | -------- | ------------------- |
| `x-api-key` | string | Yes      | Your Munsit API key |

## Message Types

### Initialize Connection

After establishing the WebSocket connection, you must send an initialization message.

**Request**:

```json theme={null}
{
  "type": "initConnection",
  "model_id": "faseeh-v1-preview",
  "voice_id": "ar-najdi-male-2",
  "voice_settings": {
    "stability": 0.5,
    "similarity_boost": 0.75,
    "speed": 1.0
  },
  "output_format": "pcm_24000",
  "x_api_key": "YOUR_API_KEY"
}
```

**Request Fields**:

| Field                             | Type   | Required | Description                                                                                                      |
| --------------------------------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------- |
| `type`                            | string | Yes      | Must be `"initConnection"`                                                                                       |
| `model_id`                        | string | No       | Model ID to use (default: `"faseeh-mini-v1-preview"`)                                                            |
| `voice_id`                        | string | Yes      | The voice ID to use for synthesis                                                                                |
| `voice_settings`                  | object | No       | Voice configuration                                                                                              |
| `voice_settings.stability`        | number | No       | Stability setting (default: 0.5)                                                                                 |
| `voice_settings.similarity_boost` | number | No       | Similarity boost (default: 0.75)                                                                                 |
| `voice_settings.speed`            | number | No       | Speed setting, range 0.7-1.2 (default: 1.0)                                                                      |
| `output_format`                   | string | No       | Audio output format. Options: `"pcm_8000"`, `"pcm_16000"`, `"pcm_22050"`, `"pcm_24000"` (default: `"pcm_24000"`) |
| `x_api_key`                       | string | No       | API key (if not provided in query parameter)                                                                     |

**Response**:

```json theme={null}
{
  "type": "connectionInitialized"
}
```

### Send Text

Send text chunks for audio generation.

**Request**:

```json theme={null}
{
  "type": "text",
  "text": "مرحبا بك في فصيح ",
  "flush": false,
  "try_trigger_generation": false
}
```

**Request Fields**:

| Field                    | Type    | Required | Description                                                          |
| ------------------------ | ------- | -------- | -------------------------------------------------------------------- |
| `type`                   | string  | Yes      | Must be `"text"`                                                     |
| `text`                   | string  | Yes      | Text to convert to speech                                            |
| `flush`                  | boolean | No       | Force generation of audio even if buffer is small (default: `false`) |
| `try_trigger_generation` | boolean | No       | Attempt to trigger generation immediately (default: `false`)         |

**Response**:

```json theme={null}
{
  "audio": "base64_encoded_audio_data",
  "sampleRate": 24000
}
```

**Response Fields**:

| Field        | Type   | Description                                   |
| ------------ | ------ | --------------------------------------------- |
| `audio`      | string | Base64-encoded PCM audio data                 |
| `sampleRate` | number | Sample rate of the audio (typically 24000 Hz) |

### Clear Buffer

Clear the current text buffer.

**Request**:

```json theme={null}
{
  "type": "clear"
}
```

**Response**: No response message.

### Close Connection

Close the WebSocket connection gracefully.

**Request**:

```json theme={null}
{
  "type": "closeConnection"
}
```

**Response**: Connection closes.

## Error Responses

If an error occurs, you'll receive:

```json theme={null}
{
  "type": "error",
  "errorCode": 40101,
  "errorMessage": "Invalid API key"
}
```

**Error Response Fields**:

| Field          | Type   | Description                             |
| -------------- | ------ | --------------------------------------- |
| `type`         | string | Always `"error"`                        |
| `errorCode`    | number | Numeric error code (e.g., 40101, 40001) |
| `errorMessage` | string | Human-readable error message            |

## Example Usage

```javascript theme={null}
const ws = new WebSocket('wss://api.munsit.com/api/v1/websocket/text-to-speech?x-api-key=YOUR_API_KEY');

ws.onopen = () => {
  // Initialize connection
  ws.send(JSON.stringify({
    type: "initConnection",
    model_id: "faseeh-v1-preview",
    voice_id: "ar-najdi-male-2",
    voice_settings: {
      stability: 0.5,
      similarity_boost: 0.75,
      speed: 1.0
    },
    output_format: "pcm_24000"
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  if (data.type === "connectionInitialized") {
    // Connection ready, send text
    ws.send(JSON.stringify({
      type: "text",
      text: "مرحبا بك في فصيح "
    }));
  } else if (data.audio) {
    // Process audio chunk
    const audioData = atob(data.audio);
    // Handle audio playback
  } else if (data.type === "error" || data.errorCode) {
    console.error("Error:", data.errorMessage);
  }
};

ws.onerror = (error) => {
  console.error("WebSocket error:", error);
};

ws.onclose = () => {
  console.log("WebSocket closed");
};
```

## Best Practices

1. **Always initialize**: Send `initConnection` immediately after opening the connection
2. **Handle errors**: Check for error messages in responses
3. **Flush when done**: Use `flush: true` when sending the last text chunk to ensure all audio is generated
4. **Close gracefully**: Send `closeConnection` before closing the WebSocket
5. **Buffer audio**: Collect audio chunks and play them sequentially for smooth playback


## AsyncAPI

````yaml api-reference/asyncapi.json text-to-speech
id: text-to-speech
title: Text-to-speech
description: ''
servers:
  - id: production
    protocol: wss
    host: api.munsit.com
    bindings: []
    variables: []
address: wss://api.munsit.com/api/v1/websocket/text-to-speech
parameters: []
bindings:
  - protocol: ws
    version: latest
    value:
      query:
        type: object
        properties:
          x-api-key:
            type: string
            description: Your Munsit API key
        required:
          - x-api-key
    schemaProperties:
      - name: query
        type: object
        required: false
        properties:
          - name: x-api-key
            type: string
            description: Your Munsit API key
            required: true
operations:
  - &ref_2
    id: sendInitConnection
    title: Send init connection
    type: send
    messages:
      - &ref_7
        id: initConnection
        payload:
          - name: Initialize Connection
            description: Initialize the WebSocket connection
            type: object
            properties:
              - name: type
                type: string
                description: initConnection
                required: true
              - name: model_id
                type: string
                required: false
              - name: voice_id
                type: string
                required: true
              - name: voice_settings
                type: object
                required: false
                properties:
                  - name: stability
                    type: number
                    required: false
                  - name: similarity_boost
                    type: number
                    required: false
                  - name: speed
                    type: number
                    required: false
              - name: output_format
                type: string
                description: Audio output format
                enumValues:
                  - pcm_8000
                  - pcm_16000
                  - pcm_22050
                  - pcm_24000
                required: false
              - name: x_api_key
                type: string
                required: false
        headers: []
        jsonPayloadSchema:
          type: object
          required:
            - type
            - voice_id
          properties:
            type:
              type: string
              const: initConnection
              x-parser-schema-id: <anonymous-schema-2>
            model_id:
              type: string
              default: faseeh-mini-v1-preview
              x-parser-schema-id: <anonymous-schema-3>
            voice_id:
              type: string
              x-parser-schema-id: <anonymous-schema-4>
            voice_settings:
              type: object
              properties:
                stability:
                  type: number
                  default: 0.5
                  x-parser-schema-id: <anonymous-schema-6>
                similarity_boost:
                  type: number
                  default: 0.75
                  x-parser-schema-id: <anonymous-schema-7>
                speed:
                  type: number
                  default: 1
                  minimum: 0.7
                  maximum: 1.2
                  x-parser-schema-id: <anonymous-schema-8>
              x-parser-schema-id: <anonymous-schema-5>
            output_format:
              type: string
              enum:
                - pcm_8000
                - pcm_16000
                - pcm_22050
                - pcm_24000
              default: pcm_24000
              description: Audio output format
              x-parser-schema-id: <anonymous-schema-9>
            x_api_key:
              type: string
              x-parser-schema-id: <anonymous-schema-10>
          x-parser-schema-id: <anonymous-schema-1>
        title: Initialize Connection
        description: Initialize the WebSocket connection
        example: |-
          {
            "type": "<string>",
            "model_id": "<string>",
            "voice_id": "<string>",
            "voice_settings": {
              "stability": 123,
              "similarity_boost": 123,
              "speed": 123
            },
            "output_format": "<string>",
            "x_api_key": "<string>"
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: initConnection
    bindings: []
    extensions: &ref_0
      - id: x-parser-unique-object-id
        value: text-to-speech
  - &ref_3
    id: sendText
    title: Send text
    type: send
    messages:
      - &ref_8
        id: text
        payload:
          - name: Send Text
            description: Send text for audio generation
            type: object
            properties:
              - name: type
                type: string
                description: text
                required: true
              - name: text
                type: string
                required: true
              - name: flush
                type: boolean
                required: false
              - name: try_trigger_generation
                type: boolean
                required: false
        headers: []
        jsonPayloadSchema:
          type: object
          required:
            - type
            - text
          properties:
            type:
              type: string
              const: text
              x-parser-schema-id: <anonymous-schema-12>
            text:
              type: string
              x-parser-schema-id: <anonymous-schema-13>
            flush:
              type: boolean
              default: false
              x-parser-schema-id: <anonymous-schema-14>
            try_trigger_generation:
              type: boolean
              default: false
              x-parser-schema-id: <anonymous-schema-15>
          x-parser-schema-id: <anonymous-schema-11>
        title: Send Text
        description: Send text for audio generation
        example: |-
          {
            "type": "<string>",
            "text": "<string>",
            "flush": true,
            "try_trigger_generation": true
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: text
    bindings: []
    extensions: *ref_0
  - &ref_1
    id: receiveAudio
    title: Receive audio
    type: receive
    messages:
      - &ref_4
        id: audio
        payload:
          - name: Audio Response
            description: Audio chunk response
            type: object
            properties:
              - name: audio
                type: string
                description: Base64-encoded PCM audio data
                required: true
              - name: sampleRate
                type: number
                required: false
        headers: []
        jsonPayloadSchema:
          type: object
          required:
            - audio
          properties:
            audio:
              type: string
              description: Base64-encoded PCM audio data
              x-parser-schema-id: <anonymous-schema-23>
            sampleRate:
              type: number
              default: 24000
              x-parser-schema-id: <anonymous-schema-24>
          x-parser-schema-id: <anonymous-schema-22>
        title: Audio Response
        description: Audio chunk response
        example: |-
          {
            "audio": "<string>",
            "sampleRate": 123
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: audio
      - &ref_5
        id: connectionInitialized
        payload:
          - name: Connection Initialized
            description: Response confirming connection initialization
            type: object
            properties:
              - name: type
                type: string
                description: connectionInitialized
                required: true
        headers: []
        jsonPayloadSchema:
          type: object
          required:
            - type
          properties:
            type:
              type: string
              const: connectionInitialized
              x-parser-schema-id: <anonymous-schema-21>
          x-parser-schema-id: <anonymous-schema-20>
        title: Connection Initialized
        description: Response confirming connection initialization
        example: |-
          {
            "type": "<string>"
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: connectionInitialized
      - &ref_6
        id: error
        payload:
          - name: Error
            description: Error response
            type: object
            properties:
              - name: type
                type: string
                description: error
                required: true
              - name: errorCode
                type: number
                description: Numeric error code
                required: true
              - name: errorMessage
                type: string
                description: Human-readable error message
                required: true
        headers: []
        jsonPayloadSchema:
          type: object
          required:
            - type
            - errorCode
            - errorMessage
          properties:
            type:
              type: string
              const: error
              x-parser-schema-id: <anonymous-schema-26>
            errorCode:
              type: number
              description: Numeric error code
              x-parser-schema-id: <anonymous-schema-27>
            errorMessage:
              type: string
              description: Human-readable error message
              x-parser-schema-id: <anonymous-schema-28>
          x-parser-schema-id: <anonymous-schema-25>
        title: Error
        description: Error response
        example: |-
          {
            "type": "<string>",
            "errorCode": 123,
            "errorMessage": "<string>"
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: error
    bindings: []
    extensions: *ref_0
sendOperations:
  - *ref_1
receiveOperations:
  - *ref_2
  - *ref_3
sendMessages:
  - *ref_4
  - *ref_5
  - *ref_6
receiveMessages:
  - *ref_7
  - *ref_8
extensions:
  - id: x-parser-unique-object-id
    value: text-to-speech
securitySchemes: []

````