Tutorial

How to Use eidosSpeech API: Complete Tutorial with Code Examples

Learn how to integrate eidosSpeech text-to-speech API into your applications with step-by-step examples in Python, JavaScript, Node.js, and cURL.

eidosSpeech API integration code example

Prerequisites

Before you start, you'll need:

Step 1: Get Your API Key

After registering, navigate to your dashboard and copy your API key. It starts with esk_ and looks like this:

esk_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6

Important: Keep your API key secret. Never commit it to public repositories or share it publicly.

Step 2: Make Your First Request

Let's start with the simplest example using cURL:

cURL
curl -X POST https://eidosspeech.xyz/api/v1/tts \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Hello from eidosSpeech!",
    "voice": "en-US-JennyNeural"
  }' \
  --output hello.mp3

This generates an MP3 file with a female American voice saying "Hello from eidosSpeech!"

Python Integration

Python is perfect for automation and backend services. Here's a complete example:

Basic Example

Python
import requests

API_KEY = "your_api_key_here"
API_URL = "https://eidosspeech.xyz/api/v1/tts"

def generate_speech(text, voice="en-US-JennyNeural", output_file="output.mp3"):
    headers = {
        "X-API-Key": API_KEY,
        "Content-Type": "application/json"
    }
    
    payload = {
        "text": text,
        "voice": voice
    }
    
    response = requests.post(API_URL, json=payload, headers=headers)
    
    if response.status_code == 200:
        with open(output_file, "wb") as f:
            f.write(response.content)
        print(f"✓ Audio saved to {output_file}")
    else:
        print(f"✗ Error: {response.status_code}")
        print(response.json())

# Usage
generate_speech("Hello world!", "en-US-GuyNeural", "hello.mp3")

Advanced Example with Voice Customization

Python
import requests

class EidosSpeechClient:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://eidosspeech.xyz/api/v1"
        self.headers = {
            "X-API-Key": api_key,
            "Content-Type": "application/json"
        }
    
    def generate(self, text, voice="en-US-JennyNeural", 
                 rate="+0%", pitch="+0Hz", volume="+0%",
                 style=None, style_degree=1.0):
        """Generate speech with custom parameters"""
        payload = {
            "text": text,
            "voice": voice,
            "rate": rate,
            "pitch": pitch,
            "volume": volume
        }
        
        # Add style if supported
        if style:
            payload["style"] = style
            payload["style_degree"] = style_degree
        
        response = requests.post(
            f"{self.base_url}/tts",
            json=payload,
            headers=self.headers
        )
        
        return response
    
    def generate_with_subtitle(self, text, voice="en-US-JennyNeural"):
        """Generate speech with subtitle file"""
        payload = {"text": text, "voice": voice}
        
        response = requests.post(
            f"{self.base_url}/tts/subtitle",
            json=payload,
            headers=self.headers
        )
        
        return response.json()
    
    def generate_multi_voice(self, script, voice_map, pause_ms=500):
        """Generate multi-voice dialog"""
        payload = {
            "script": script,
            "voice_map": voice_map,
            "pause_ms": pause_ms
        }
        
        response = requests.post(
            f"{self.base_url}/tts/script",
            json=payload,
            headers=self.headers
        )
        
        return response

# Usage
client = EidosSpeechClient("your_api_key")

# Basic generation
response = client.generate("Hello world!", "en-US-JennyNeural")
with open("output.mp3", "wb") as f:
    f.write(response.content)

# With emotion
response = client.generate(
    "I'm so excited!",
    voice="en-US-AriaNeural",
    style="excited",
    style_degree=1.5
)

# Multi-voice dialog
script = """[John]: Hello, how are you?
[Mary]: I'm doing great, thanks!"""

voice_map = {
    "John": "en-US-GuyNeural",
    "Mary": "en-US-JennyNeural"
}

response = client.generate_multi_voice(script, voice_map)
with open("dialog.mp3", "wb") as f:
    f.write(response.content)
Python code example for eidosSpeech API integration

JavaScript / Node.js Integration

Perfect for web applications and Node.js backends:

Browser JavaScript (Fetch API)

JavaScript
async function generateSpeech(text, voice = 'en-US-JennyNeural') {
    const API_KEY = 'your_api_key_here';
    const API_URL = 'https://eidosspeech.xyz/api/v1/tts';
    
    try {
        const response = await fetch(API_URL, {
            method: 'POST',
            headers: {
                'X-API-Key': API_KEY,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ text, voice })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const blob = await response.blob();
        const url = URL.createObjectURL(blob);
        
        // Play audio
        const audio = new Audio(url);
        audio.play();
        
        // Or download
        const a = document.createElement('a');
        a.href = url;
        a.download = 'speech.mp3';
        a.click();
        
        return url;
    } catch (error) {
        console.error('Error:', error);
    }
}

// Usage
generateSpeech('Hello from JavaScript!', 'en-US-GuyNeural');

Node.js with Axios

Node.js
const axios = require('axios');
const fs = require('fs');

class EidosSpeechClient {
    constructor(apiKey) {
        this.apiKey = apiKey;
        this.baseURL = 'https://eidosspeech.xyz/api/v1';
    }
    
    async generate(text, voice = 'en-US-JennyNeural', options = {}) {
        try {
            const response = await axios.post(
                `${this.baseURL}/tts`,
                {
                    text,
                    voice,
                    ...options
                },
                {
                    headers: {
                        'X-API-Key': this.apiKey,
                        'Content-Type': 'application/json'
                    },
                    responseType: 'arraybuffer'
                }
            );
            
            return response.data;
        } catch (error) {
            console.error('Error:', error.response?.data || error.message);
            throw error;
        }
    }
    
    async saveToFile(text, voice, filename) {
        const audioData = await this.generate(text, voice);
        fs.writeFileSync(filename, audioData);
        console.log(`✓ Saved to ${filename}`);
    }
}

// Usage
const client = new EidosSpeechClient('your_api_key');

client.saveToFile(
    'Hello from Node.js!',
    'en-US-JennyNeural',
    'output.mp3'
);

Rate Limit Handling

Every response includes rate limit headers. Here's how to handle them:

Python
import requests
import time

def generate_with_retry(text, voice, max_retries=3):
    for attempt in range(max_retries):
        response = requests.post(
            "https://eidosspeech.xyz/api/v1/tts",
            json={"text": text, "voice": voice},
            headers={"X-API-Key": API_KEY}
        )
        
        # Check rate limit headers
        remaining = int(response.headers.get('X-RateLimit-Remaining-Day', 0))
        limit = int(response.headers.get('X-RateLimit-Limit-Day', 30))
        
        print(f"Rate limit: {remaining}/{limit} remaining")
        
        if response.status_code == 200:
            return response.content
        elif response.status_code == 429:
            retry_after = int(response.headers.get('Retry-After', 60))
            print(f"Rate limited. Retrying after {retry_after}s...")
            time.sleep(retry_after)
        else:
            print(f"Error: {response.status_code}")
            break
    
    return None

Error Handling Best Practices

Always handle errors gracefully:

Python
import requests

def safe_generate(text, voice):
    try:
        response = requests.post(
            "https://eidosspeech.xyz/api/v1/tts",
            json={"text": text, "voice": voice},
            headers={"X-API-Key": API_KEY},
            timeout=30  # 30 second timeout
        )
        
        response.raise_for_status()
        return response.content
        
    except requests.exceptions.Timeout:
        print("Request timed out")
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            print("Invalid API key")
        elif e.response.status_code == 429:
            print("Rate limit exceeded")
        else:
            print(f"HTTP error: {e}")
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
    
    return None

Common Use Cases

1. Batch Processing

Convert multiple texts to speech:

Python
texts = [
    "Chapter 1: Introduction",
    "Chapter 2: Getting Started",
    "Chapter 3: Advanced Topics"
]

for i, text in enumerate(texts, 1):
    response = client.generate(text, "en-US-JennyNeural")
    with open(f"chapter_{i}.mp3", "wb") as f:
        f.write(response.content)
    print(f"✓ Generated chapter {i}")
    time.sleep(1)  # Rate limit friendly

2. Dynamic Voice Selection

Choose voice based on language:

Python
VOICE_MAP = {
    'en': 'en-US-JennyNeural',
    'id': 'id-ID-GadisNeural',
    'ja': 'ja-JP-NanamiNeural',
    'es': 'es-ES-ElviraNeural'
}

def generate_multilingual(text, lang_code):
    voice = VOICE_MAP.get(lang_code, 'en-US-JennyNeural')
    return client.generate(text, voice)

3. Subtitle Generation for Videos

Python
result = client.generate_with_subtitle(
    "Welcome to our tutorial video",
    "en-US-GuyNeural"
)

# Save audio
audio_url = result['audio_url']
# Download from audio_url

# Save subtitle
with open('subtitle.srt', 'w') as f:
    f.write(result['subtitle'])

print("✓ Audio and subtitle generated!")

Tips & Best Practices

Troubleshooting

401 Unauthorized

Problem: Invalid or missing API key

Solution: Check your API key in the dashboard and ensure it's correctly set in headers

429 Too Many Requests

Problem: Rate limit exceeded

Solution: Wait for the time specified in Retry-After header or upgrade your tier

400 Bad Request

Problem: Invalid request data

Solution: Check your JSON payload matches the API schema

Next Steps

Now that you know how to use the API, explore advanced features:

Start Building with eidosSpeech API

Free forever. 1,200+ voices. 75+ languages.

e
eidosSpeech Team
Building free tools for developers and creators

Related Articles