Response Formats

Understanding API responses for text-to-speech requests.

Successful Response

A successful TTS generation returns binary audio data:

HeaderValue
Status Code200 OK
Content-Typeaudio/mpeg (or format-specific)
Content-LengthSize in bytes
X-Credits-UsedCredits consumed
X-Duration-MsAudio duration in milliseconds

Content-Type by Format

FormatContent-Type
mp3audio/mpeg
wavaudio/wav
oggaudio/ogg
flacaudio/flac
aacaudio/aac

Handling the Response

Python

import requests

response = requests.post(
    "https://yourvoic.com/api/v1/tts/generate",
    headers={"X-API-Key": "your_api_key"},
    json={
        "text": "Hello, world!",
        "voice": "Peter",
        "language": "en-US"
    }
)

if response.status_code == 200:
    # Save the audio file
    with open("output.mp3", "wb") as f:
        f.write(response.content)
    
    # Access response headers
    credits_used = response.headers.get("X-Credits-Used")
    duration_ms = response.headers.get("X-Duration-Ms")
    
    print(f"Credits used: {credits_used}")
    print(f"Duration: {duration_ms}ms")
else:
    # Handle error
    error = response.json()
    print(f"Error: {error}")

JavaScript

const response = await fetch('https://yourvoic.com/api/v1/tts/generate', {
    method: 'POST',
    headers: {
        'X-API-Key': 'your_api_key',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        text: 'Hello, world!',
        voice: 'Peter',
        language: 'en-US'
    })
});

if (response.ok) {
    // Get audio as blob
    const audioBlob = await response.blob();
    
    // Access headers
    const creditsUsed = response.headers.get('X-Credits-Used');
    const durationMs = response.headers.get('X-Duration-Ms');
    
    // Play in browser
    const audioUrl = URL.createObjectURL(audioBlob);
    const audio = new Audio(audioUrl);
    audio.play();
} else {
    const error = await response.json();
    console.error('Error:', error);
}

Error Response

When an error occurs, the API returns JSON with error details:

{
    "success": false,
    "error": {
        "code": "INVALID_VOICE",
        "message": "Voice 'InvalidVoice' not found.",
        "details": {
            "provided": "InvalidVoice",
            "available": ["Peter", "Emma", "James", "..."]
        }
    }
}

Error Response Fields

FieldTypeDescription
successbooleanAlways false for errors
error.codestringMachine-readable error code
error.messagestringHuman-readable description
error.detailsobjectAdditional context (optional)

Streaming Response

For streaming endpoints, audio is sent in chunks:

response = requests.post(
    "https://yourvoic.com/api/v1/tts/generate/stream",
    headers={"X-API-Key": "your_api_key"},
    json={"text": "Streaming audio...", "voice": "Peter"},
    stream=True
)

# Process chunks as they arrive
for chunk in response.iter_content(chunk_size=4096):
    if chunk:
        # Play or save each chunk
        process_audio_chunk(chunk)

Voices Endpoint Response

{
    "success": true,
    "voices": [
        {
            "id": "peter",
            "name": "Peter",
            "gender": "male",
            "age": "middle",
            "style": "narrative",
            "languages": ["en-US", "en-GB", "en-AU"],
            "sample_url": "https://yourvoic.com/samples/peter.mp3"
        },
        {
            "id": "emma",
            "name": "Emma",
            "gender": "female",
            "age": "young",
            "style": "conversational",
            "languages": ["en-US", "en-GB"],
            "sample_url": "https://yourvoic.com/samples/emma.mp3"
        }
    ],
    "total": 30
}

Credits Endpoint Response

{
    "success": true,
    "credits": {
        "balance": 10000,
        "used_this_month": 2500,
        "plan": "pro",
        "renewal_date": "2024-02-01"
    }
}