> ## 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.

# Generate Streamed Text to Speech File Data

> From the user's perspective, this is a standard request. In the response, we include specific headers: 'Transfer-Encoding' is set to 'chunked' to enable streaming, 'Connection' is set to 'keep-alive' to maintain the connection, and 'Content-Type' is set to 'audio/wav' to indicate the media type. These headers allow the client to stream audio data from the server in real time.  Important Note: after collecting the chunks, you need to add the wav header manually to the data. If you wish to get a wav header, please use the [Generate TTS File Data API](/api-reference/endpoint/rt-generate-tts).



## OpenAPI

````yaml /api-reference/openapi.json post /v1/realtime/tts-stream
openapi: 3.0.1
info:
  title: Hamsa API
  description: Trying out our transcription and media-to-text APIs
  license:
    name: MIT
  version: 1.0.0
servers:
  - url: https://api.tryhamsa.com
security: []
paths:
  /v1/realtime/tts-stream:
    post:
      summary: Generates a streamed audio file from a text string.
      description: >-
        From the user's perspective, this is a standard request. In the
        response, we include specific headers: 'Transfer-Encoding' is set to
        'chunked' to enable streaming, 'Connection' is set to 'keep-alive' to
        maintain the connection, and 'Content-Type' is set to 'audio/wav' to
        indicate the media type. These headers allow the client to stream audio
        data from the server in real time.  Important Note: after collecting the
        chunks, you need to add the wav header manually to the data. If you wish
        to get a wav header, please use the [Generate TTS File Data
        API](/api-reference/endpoint/rt-generate-tts).
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RtTtsRequest'
      responses:
        '200':
          description: Streamed Successful Response - Chunked
          content:
            stream:
              schema:
                type: string
                format: binary
                example: '00000000: 52 49 46 46 FF FF FF FF 57 41 56 45 66 6D 74 20 '
                x-streaming: true
          headers:
            Transfer-Encoding:
              description: >-
                Indicates that the response uses chunked transfer encoding -
                streamed.
              schema:
                type: string
                example: chunked
            Connection:
              description: >-
                Indicates that the server will keep the connection open for
                streaming.
              schema:
                type: string
                example: keep-alive
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '500':
          description: Server Side Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
      security:
        - ApiKeyAuth: []
      x-codeSamples:
        - lang: JavaScript
          label: Stream and play audio chunks (Browser)
          source: |-
            fetch('https://api.tryhamsa.com/v1/realtime/tts-stream', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Token YOUR_API_KEY'
              },
              body: JSON.stringify({ speaker: 'Ali', dialect: 'pls', text: 'Hello, world!', mulaw: false })
            })
            .then(response => {
              const reader = response.body.getReader();
              const chunks = [];

              function read() {
                reader.read().then(({ done, value }) => {
                  if (done) {
                    // Concatenate chunks and play entire stream
                    const blob = new Blob(chunks, { type: 'audio/wav' });
                    const url = URL.createObjectURL(blob);
                    const audio = new Audio(url);
                    audio.play();
                    return;
                  }

                  chunks.push(value);
                  read();
                });
              }

              read();
            })
            .catch(console.error);
        - lang: JavaScript
          label: Stream and save audio (Node.js)
          source: |-
            // For Node.js environments
            // npm install node-fetch
            import fetch from 'node-fetch';
            import * as fs from 'fs';

            fetch('https://api.tryhamsa.com/v1/realtime/tts-stream', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Token YOUR_API_KEY'
              },
              body: JSON.stringify({ speaker: 'Ali', dialect: 'pls', text: 'Hello, world!', mulaw: false })
            })
            .then(response => {
              if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
              }
              
              // Create a write stream for the output file
              const fileStream = fs.createWriteStream('hamsa-output.wav');
              
              // Pipe the response body directly to the file
              response.body.pipe(fileStream);
              
              return new Promise((resolve, reject) => {
                response.body.on('error', reject);
                fileStream.on('finish', resolve);
              });
            })
            .then(() => {
              console.log('Audio saved to hamsa-output.wav');
            })
            .catch(console.error);
components:
  schemas:
    RtTtsRequest:
      type: object
      properties:
        text:
          type: string
          description: The text to be generated as an aduio file.
          example: مرحباً بكم في جميعاً في همسة!
        speaker:
          type: string
          description: >-
            The speaker (voice) name. Pick a voice that matches the chosen
            dialect — see the `dialect` field for voice examples per dialect.
            You can also pass the UUID of a custom cloned voice, but you must
            first preload it via the [Preload Cloned Voice
            endpoint](/src/api-reference/endpoint/preload-cloned-tts-voice).
          example: Amjad
        dialect:
          type: string
          enum:
            - pls
            - egy
            - syr
            - irq
            - jor
            - leb
            - ksa
            - uae
            - bah
            - qat
            - kuw
            - oma
            - msa
            - ar-sa
            - en
          description: >-
            The dialect to synthesize, identified by its country/region code.
            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` (Modern Standard Arabic / Fusha) — Salem, Tamim

            - `ar-sa` (Arabic – Gulf) — Khalid, Rahma

            - `en` (English) — Emma, James
          example: pls
        mulaw:
          type: boolean
          description: Whether to use 'Mu-Law' algorithm in voice signal processing or not.
          example: false
          default: false
        sampleRate:
          type: string
          enum:
            - 8k
            - 16k
          description: >-
            Output sample rate of the PCM audio. Defaults to `16k`. Only applies
            to PCM output — cannot be combined with `mulaw` (mu-law output is
            always 8 kHz).
          default: 16k
          example: 16k
        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.
          minimum: 0
          maximum: 2
          default: 1
          example: 1
      required:
        - text
        - speaker
    ErrorSchema:
      type: object
      properties:
        code:
          type: integer
        message:
          type: string
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: Authorization
      description: >-
        Pass the API key in the Authorization header, You need to put Token
        keyword before the API key. e.g. 'Authorization: Token <api-key>'

````