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

# Text-to-Speech

> Generate natural-sounding speech from text using AI voice models

Generate high-quality speech audio from text using our collection of state-of-the-art text-to-speech models from leading AI providers.

## Create Speech

`POST /audio/speech`

Convert text to natural-sounding speech audio.

### Request Body

<ParamField body="model" type="string" required>
  The TTS model to use for speech generation (e.g., "tts-1", "tts-1-hd", "elevenlabs")
</ParamField>

#### Text Input Parameters

<ParamField body="input" type="string">
  The text to convert to speech (1-4096 characters)
</ParamField>

#### Voice Parameters

<ParamField body="voice" type="string">
  Voice name or ID for speech generation
</ParamField>

#### Common Parameters

<ParamField body="response_format" type="string">
  The audio format for the generated speech ("mp3", "opus", "aac", "flac", "wav", "pcm")
</ParamField>

<ParamField body="speed" type="number">
  The speed of the generated audio (0.25 to 4.0 for most models, default: 1.0)
</ParamField>

<ParamField body="temperature" type="number">
  Temperature for randomness in speech generation (0.0 to 2.0)
</ParamField>

#### Advanced Parameters

<ParamField body="instructions" type="string">
  **GPT-4o Mini TTS**: Additional instructions to control voice characteristics
</ParamField>

<ParamField body="speaker_transcript" type="string">
  **Dia model**: Speaker transcript for enhanced voice control (max 1000 chars)
</ParamField>

<ParamField body="cfg_filter_top_k" type="integer">
  **Dia model**: CFG filter top k value (15-50)
</ParamField>

<ParamField body="cfg_scale" type="integer">
  **Dia model**: CFG scale value for generation control (1-5)
</ParamField>

<ParamField body="speech_rate" type="integer">
  **Microsoft TTS**: Speech rate adjustment (-100 to 100, default: 0)
</ParamField>

<ParamField body="pitch_adjustment" type="integer">
  **Microsoft TTS**: Pitch adjustment (-100 to 100, default: 0)
</ParamField>

<ParamField body="emotional_style" type="string">
  **Microsoft TTS**: Emotional style (e.g., "cheerful", "sad", "angry")
</ParamField>

### Response

Returns an audio file in the specified format.

### Basic Example

<CodeGroup>
  ```javascript Node.js theme={null}
  const response = await fetch('https://api.electronhub.ai/v1/audio/speech', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'tts-1',
      input: 'Hello! Welcome to Electron Hub text-to-speech.',
      voice: 'alloy',
      response_format: 'mp3'
    })
  });

  const audioBuffer = await response.arrayBuffer();
  const fs = require('fs');
  fs.writeFileSync('speech.mp3', Buffer.from(audioBuffer));
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'https://api.electronhub.ai/v1/audio/speech',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'model': 'tts-1',
          'input': 'Hello! Welcome to Electron Hub text-to-speech.',
          'voice': 'alloy',
          'response_format': 'mp3'
      }
  )

  with open('speech.mp3', 'wb') as f:
      f.write(response.content)
  ```

  ```bash cURL theme={null}
  curl https://api.electronhub.ai/v1/audio/speech \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "tts-1",
      "input": "Hello! Welcome to Electron Hub text-to-speech.",
      "voice": "alloy",
      "response_format": "mp3"
    }' \
    --output speech.mp3
  ```
</CodeGroup>

## Provider-Specific Examples

### OpenAI Models (TTS-1, TTS-1 HD, GPT-4o Mini TTS)

<CodeGroup>
  ```javascript OpenAI Standard theme={null}
  {
    "model": "tts-1",
    "input": "Hello, world!",
    "voice": "alloy",
    "speed": 1.0
  }
  ```

  ```javascript GPT-4o Mini TTS with Instructions theme={null}
  {
    "model": "gpt-4o-mini-tts",
    "input": "Welcome to our store!",
    "voice": "nova",
    "instructions": "Speak with enthusiasm and excitement, like a friendly shopkeeper"
  }
  ```
</CodeGroup>

### ElevenLabs Models

<CodeGroup>
  ```javascript ElevenLabs theme={null}
  {
    "model": "elevenlabs",
    "input": "Hello, this is ElevenLabs TTS.",
    "voice": "Will (US male)"
  }
  ```

  ```python Python - ElevenLabs theme={null}
  requests.post(
      'https://api.electronhub.ai/v1/audio/speech',
      json={
          'model': 'elevenlabs',
          'input': 'Bonjour, je parle français!',
          'voice': 'Guillaume (French male)'
      }
  )
  ```
</CodeGroup>

### Kokoro 82M Model

<CodeGroup>
  ```javascript Kokoro theme={null}
  {
    "model": "kokoro-82m",
    "input": "Hello from Kokoro TTS!",
    "voice": "af_alloy",
    "speed": 1.2
  }
  ```

  ```python Python - Kokoro theme={null}
  requests.post(
      'https://api.electronhub.ai/v1/audio/speech',
      json={
          'model': 'kokoro-82m',
          'input': 'こんにちは、世界！',
          'voice': 'jf_alpha'
      }
  )
  ```
</CodeGroup>

### NariLabs Dia Model (Advanced)

<CodeGroup>
  ```javascript Dia Advanced theme={null}
  {
    "model": "dia-1.6b",
    "input": "Hello, this is a conversational speech example.",
    "speaker_transcript": "Speaking in a calm, professional tone",
    "cfg_scale": 3,
    "cfg_filter_top_k": 25,
    "temperature": 1.2,
    "speed": 0.9
  }
  ```

  ```python Python - Dia theme={null}
  requests.post(
      'https://api.electronhub.ai/v1/audio/speech',
      json={
          'model': 'dia-1.6b',
          'input': 'Let me tell you a story...',
          'speaker_transcript': 'Narrator voice with dramatic pauses',
          'cfg_scale': 4,
          'temperature': 1.3
      }
  )
  ```
</CodeGroup>

### MeloTTS Multilingual

<CodeGroup>
  ```javascript MeloTTS theme={null}
  {
    "model": "melotts",
    "input": "Bonjour, comment allez-vous?",
    "voice": "fr"
  }
  ```

  ```python Python - MeloTTS Languages theme={null}
  # English
  requests.post('/v1/audio/speech', json={'model': 'melotts', 'input': 'Hello world', 'voice': 'en'})

  # Spanish  
  requests.post('/v1/audio/speech', json={'model': 'melotts', 'input': 'Hola mundo', 'voice': 'es'})

  # Chinese
  requests.post('/v1/audio/speech', json={'model': 'melotts', 'input': '你好世界', 'voice': 'zh'})
  ```
</CodeGroup>

### PlayAI Dialog Models

<CodeGroup>
  ```javascript PlayAI theme={null}
  {
    "model": "playai-tts",
    "input": "This is a conversational AI speaking.",
    "voice": "Celeste-PlayAI",
    "temperature": 0.8
  }
  ```

  ```python Python - PlayAI Arabic theme={null}
  requests.post(
      'https://api.electronhub.ai/v1/audio/speech',
      json={
          'model': 'playai-tts-arabic',
          'input': 'مرحبا بكم في الذكاء الاصطناعي',
          'voice': 'Nasser-PlayAI'
      }
  )
  ```
</CodeGroup>

### Microsoft TTS

<CodeGroup>
  ```javascript Microsoft Basic theme={null}
  {
    "model": "microsoft-tts",
    "input": "Hello, this is Microsoft Azure Text-to-Speech.",
    "voice": "en-US-JennyNeural"
  }
  ```

  ```javascript Microsoft Advanced theme={null}
  {
    "model": "microsoft-tts",
    "input": "Welcome to our exciting new product launch!",
    "voice": "en-US-AriaNeural",
    "speech_rate": 10,
    "pitch_adjustment": 5,
    "emotional_style": "cheerful"
  }
  ```

  ```python Python - Microsoft Multilingual theme={null}
  requests.post(
      'https://api.electronhub.ai/v1/audio/speech',
      json={
          'model': 'microsoft-tts',
          'input': '你好，欢迎使用微软语音合成服务！',
          'voice': 'zh-CN-XiaoxiaoNeural',
          'speech_rate': -10,
          'emotional_style': 'gentle'
      }
  )
  ```

  ```python Python - Microsoft Emotional theme={null}
  requests.post(
      'https://api.electronhub.ai/v1/audio/speech',
      json={
          'model': 'microsoft-tts',
          'input': 'I am so sorry to hear about that.',
          'voice': 'en-US-SaraNeural',
          'emotional_style': 'sad',
          'speech_rate': -20
      }
  )
  ```
</CodeGroup>

## Available Models

### OpenAI Models

**TTS-1** (`tts-1`)

* Optimized for real-time text-to-speech
* Cost-effective for most applications
* 11 available voices: alloy, ash, ballad, coral, echo, fable, onyx, nova, sage, shimmer, verse

**TTS-1 HD** (`tts-1-hd`)

* High-quality text-to-speech
* Best audio quality with slower generation
* Same 11 voices as TTS-1

**GPT-4o Mini TTS** (`gpt-4o-mini-tts`)

* Advanced TTS with instruction following
* Supports voice control via instructions
* Same 11 voices as TTS-1

### Premium Models

**ElevenLabs** (`elevenlabs`)

* Ultra-realistic human-like voices
* 40+ multilingual voices
* Supports English, Spanish, French, German, Arabic, Chinese, Hindi, Polish

**PlayAI Dialog** (`playai-tts`)

* Specialized for conversational content
* 27 expressive voices
* Optimized for dialogue and storytelling

### Specialized Models

**Kokoro 82M** (`kokoro-82m`)

* Lightweight but high-quality
* 80+ voices in multiple languages
* Open-source Apache-licensed model

**Microsoft TTS** (`microsoft-tts`)

* Enterprise-grade quality
* 100+ neural voices
* Extensive language support

## Voice Examples

### OpenAI Voices

```javascript theme={null}
// Available voices for OpenAI models
const openaiVoices = [
  'alloy',    // Neutral, balanced
  'echo',     // Clear, professional
  'fable',    // Warm, storytelling
  'onyx',     // Deep, authoritative
  'nova',     // Bright, energetic
  'shimmer'   // Gentle, soothing
];
```

### ElevenLabs Voices

```javascript theme={null}
// Sample of ElevenLabs voices by language
const elevenlabsVoices = {
  english: ['Will (US male)', 'Jessica (US female)', 'George (UK male)', 'Lily (UK female)'],
  spanish: ['Juan (Spanish male)', 'Gabriela (Spanish female)'],
  french: ['Guillaume (French male)', 'Darine (French female)'],
  german: ['Kurt (German male)', 'Leonie (German female)']
};

// Use with voice parameter and text input
{
  "model": "elevenlabs",
  "input": "Hello world",
  "voice": "Will (US male)"
}
```

### Microsoft TTS Voices

```javascript theme={null}
// Sample of Microsoft Azure Neural voices
const microsoftVoices = {
  english: [
    'en-US-JennyNeural',    // Friendly female
    'en-US-GuyNeural',      // Casual male
    'en-US-AriaNeural',     // News anchor style
    'en-US-DavisNeural',    // Professional male
    'en-GB-SoniaNeural',    // British female
    'en-AU-NatashaNeural'   // Australian female
  ],
  chinese: [
    'zh-CN-XiaoxiaoNeural',  // Standard female
    'zh-CN-YunyangNeural',   // Professional male
    'zh-HK-HiuMaanNeural',   // Hong Kong Cantonese
    'zh-TW-HsiaoChenNeural'  // Taiwan Mandarin
  ],
  multilingual: [
    'es-ES-ElviraNeural',    // Spanish
    'fr-FR-DeniseNeural',    // French
    'de-DE-KatjaNeural',     // German
    'ja-JP-NanamiNeural',    // Japanese
    'ko-KR-SunHiNeural'      // Korean
  ]
};

// Use with text input and advanced controls
{
  "model": "microsoft-tts",
  "input": "Hello world",
  "voice": "en-US-AriaNeural",
  "emotional_style": "cheerful",
  "speech_rate": 10
}
```

## Model-Specific Parameters

| Provider            | Special Parameters                                    | Usage                                 |
| ------------------- | ----------------------------------------------------- | ------------------------------------- |
| **GPT-4o Mini TTS** | `instructions`                                        | Natural language voice control        |
| **Dia 1.6B**        | `speaker_transcript`, `cfg_scale`, `cfg_filter_top_k` | Advanced voice conditioning           |
| **Microsoft TTS**   | `speech_rate`, `pitch_adjustment`, `emotional_style`  | Voice modulation and emotions         |
| **MeloTTS**         | `lang`                                                | Language selection (en, fr, es, etc.) |
| **All Models**      | `speed`, `temperature`, `top_p`                       | Common generation controls            |

## Advanced Features

### Speed Control

Adjust playback speed for different use cases:

```json theme={null}
{
  "model": "tts-1",
  "input": "This text will be spoken faster.",
  "voice": "alloy",
  "speed": 1.5
}
```

### Audio Formats

Choose the optimal format for your application:

* **MP3**: Standard, widely compatible
* **WAV**: Uncompressed, highest quality
* **OGG/Opus**: Efficient compression
* **FLAC**: Lossless compression
* **AAC**: Good balance of quality and size

### Instruction-Based Control (GPT-4o Mini TTS)

Control voice characteristics with natural language:

```json theme={null}
{
  "model": "gpt-4o-mini-tts",
  "input": "Welcome to our store!",
  "voice": "alloy",
  "instructions": "Speak with enthusiasm and excitement, like a friendly shopkeeper"
}
```

### Microsoft TTS Advanced Controls

Microsoft TTS offers fine-grained control over speech characteristics:

#### Speech Rate Control

```json theme={null}
{
  "model": "microsoft-tts",
  "input": "This text will be spoken faster.",
  "voice": "en-US-JennyNeural",
  "speech_rate": 50
}
```

#### Pitch Adjustment

```json theme={null}
{
  "model": "microsoft-tts",
  "input": "This text has a higher pitch.",
  "voice": "en-US-AriaNeural",
  "pitch_adjustment": 25
}
```

#### Emotional Styles

Different voices support different emotional styles:

```json theme={null}
{
  "model": "microsoft-tts",
  "input": "I'm so excited about this news!",
  "voice": "en-US-AriaNeural",
  "emotional_style": "cheerful",
  "speech_rate": 10
}
```

**Available Emotional Styles** (voice-dependent):

* `cheerful` - Happy and upbeat
* `sad` - Melancholic tone
* `angry` - Frustrated or upset
* `fearful` - Nervous or scared
* `calm` - Relaxed and peaceful
* `gentle` - Soft and caring
* `newscast` - Professional news anchor
* `customerservice` - Helpful and polite

## Best Practices

### Text Optimization

* Use clear punctuation for natural pauses
* Spell out numbers and abbreviations
* Use SSML tags for fine-grained control (model-dependent)

### Voice Selection

* **Customer Service**: Professional voices (echo, George)
* **Storytelling**: Warm voices (fable, nova)
* **Educational**: Clear voices (alloy, shimmer)
* **Gaming**: Character voices (onyx, sage)

### Performance Tips

* Cache generated audio when possible
* Use appropriate audio formats for your platform
* Consider real-time vs. high-quality models based on use case

## Error Handling

Common error scenarios:

```javascript theme={null}
try {
  const response = await fetch('/v1/audio/speech', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'tts-1',
      input: text,
      voice: 'alloy'
    })
  });

  if (!response.ok) {
    const error = await response.json();
    console.error('TTS Error:', error);
  }
} catch (error) {
  console.error('Network Error:', error);
}
```

## Use Cases

* **Voice Assistants**: Natural conversation interfaces
* **Audiobooks**: Long-form content narration
* **E-learning**: Educational content delivery
* **Accessibility**: Screen reader alternatives
* **Gaming**: Character voice generation
* **Customer Service**: Automated phone systems
* **Content Creation**: Podcast and video narration


## OpenAPI

````yaml POST /audio/speech
openapi: 3.0.1
info:
  title: Electron Hub API
  description: >-
    Unified API platform integrating 200+ AI models for chat, image generation,
    speech-to-text, embeddings, and more.
  version: 1.0.0
  contact:
    name: Electron Hub Support
    email: support@electronhub.ai
    url: https://discord.com/invite/electronhub
  license:
    name: MIT
servers:
  - url: https://api.electronhub.ai/v1
    description: Production API v1
security:
  - bearerAuth: []
paths:
  /audio/speech:
    post:
      summary: Create Speech
      description: Generate audio from text using text-to-speech models
      operationId: createSpeech
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AudioSpeechRequest'
      responses:
        '200':
          description: Audio file
          content:
            audio/mpeg:
              schema:
                type: string
                format: binary
            audio/wav:
              schema:
                type: string
                format: binary
            audio/ogg:
              schema:
                type: string
                format: binary
components:
  schemas:
    AudioSpeechRequest:
      type: object
      required:
        - model
      properties:
        model:
          type: string
          description: The TTS model to use for speech generation
          example: tts-1
        input:
          type: string
          description: The text to convert to speech (OpenAI models)
          minLength: 1
          maxLength: 4096
          example: Hello, world! This is a text-to-speech example.
        voice:
          type: string
          description: >-
            The voice to use for speech generation (OpenAI, Orpheus, PlayAI,
            ElevenLabs models)
          example: alloy
        response_format:
          type: string
          enum:
            - mp3
            - opus
            - aac
            - flac
            - wav
            - pcm
          default: mp3
          description: The audio format for the generated speech
        speed:
          type: number
          minimum: 0.25
          maximum: 4
          default: 1
          description: The speed of the generated audio
        temperature:
          type: number
          minimum: 0
          maximum: 2
          description: Temperature for randomness in speech generation
        top_p:
          type: number
          minimum: 0
          maximum: 1
          description: Top-p value for nucleus sampling
        instructions:
          type: string
          description: >-
            Additional instructions to control voice generation (GPT-4o Mini
            TTS)
        speaker_transcript:
          type: string
          maxLength: 1000
          description: Speaker transcript for Dia model
        cfg_filter_top_k:
          type: integer
          minimum: 15
          maximum: 50
          description: CFG filter top k value (Dia model)
        cfg_scale:
          type: integer
          minimum: 1
          maximum: 5
          description: CFG scale value (Dia model)
        speech_rate:
          type: integer
          minimum: -100
          maximum: 100
          default: 0
          description: Speech rate adjustment for Microsoft TTS (-100 to 100)
        pitch_adjustment:
          type: integer
          minimum: -100
          maximum: 100
          default: 0
          description: Pitch adjustment for Microsoft TTS (-100 to 100)
        emotional_style:
          type: string
          description: Emotional style for Microsoft TTS (e.g., 'cheerful', 'sad', 'angry')
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: Enter your API key (starts with 'ek-')

````