> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.bakbak.si/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.bakbak.si/_mcp/server.

# Bakbak TTS best practices

Follow these best practices to get the most out of Bakbak TTS API.

## Text Input and Script

### Hindi: use Devanagari, not Roman

Hindi (`hi`) must be submitted in **Devanagari** script. Romanized or Latin transliteration (for example, `namaste` instead of `नमस्ते`) is **not supported** and will produce poor results.

### English: Devanagari for Indic named entities

For English (`en-in`, `en-us`), Indic names and named entities — people, places, brands, and similar proper nouns — are pronounced much more accurately when written in **Devanagari** rather than Roman spelling.

If your text is produced by an LLM, ask it to render Indic named entities in Devanagari even when the surrounding sentence is in English. This single change can drastically improve pronunciation quality.

**Example:**

```
Please welcome Rahul from Mumbai to the stage.
```

Better for TTS:

```
Please welcome राहुल from मुंबई to the stage.
```

## Match Model to Voice

Voices are model-specific. The API supports two models: `standard` (default) and `m1`. Each has its own voice catalog returned by `GET /v1/voices`.

* Always set `model` to the same value as the voice's `model` field
* Do not reuse a `voice_id` across models — `standard` voice IDs will fail with `"model": "m1"`, and vice versa
* When switching models, fetch the voice list again and pick a voice ID from the matching catalog

## Choose the Right Endpoint

### Use Non-Streaming For:

* Batch processing multiple texts
* Content creation workflows
* Offline applications
* When you need complete files

### Use Streaming For:

* Real-time voice assistants
* Low-latency applications
* Interactive systems
* When you need immediate audio playback

## Optimize Sample Rates

* **8000 Hz**: Use for telephony and bandwidth-constrained scenarios
* **16000 Hz**: Good balance of quality and file size
* **24000 Hz**: Use for high-quality applications (default)

## Select Appropriate Audio Formats

* **WAV**: Best quality, larger files (default)
* **MP3**: Compressed, smaller files, good for web
* **PCM**: Raw format, for custom processing
* **μ-law / A-law**: Telephony standard, very small files

Ask for the format your player or telephony provider uses with `output_format`, rather than converting audio yourself. For phone calls, request `pcm_mulaw` or `pcm_alaw` at 8000 Hz. For real-time voice agents, request `pcm_s16le`, which is half the size of the default 32-bit float stream. See [Output Formats](/text-to-speech/output-formats).

## Cache Voice Lists

Voice lists don't change frequently. Cache the `/v1/voices` response to reduce API calls:

```python
# Cache voices for 1 hour
voices_cache = {}
cache_time = 0

def get_voices():
    if time.time() - cache_time > 3600:
        # Refresh cache
        response = requests.get(
            'https://hub.getraya.app/v1/voices',
            headers={'X-API-Key': 'your-api-key'}
        )
        voices_cache = response.json()
        cache_time = time.time()
    return voices_cache
```

## Handle Errors Gracefully

Always check response status codes and handle errors appropriately:

```python
response = requests.post(url, headers=headers, json=data)

if response.status_code == 200:
    # Success
    audio = response.content
elif response.status_code == 400:
    # Validation error
    error = response.json()
    print(f"Error: {error['detail']}")
elif response.status_code == 401:
    # Authentication error
    print("Invalid API key")
elif response.status_code == 429:
    # Rate limit
    print("Rate limit exceeded")
else:
    # Other errors
    print(f"Error: {response.status_code}")
```

## Optimize Text Length

For streaming endpoints, consider breaking long texts into smaller chunks:

```python
def split_text(text, max_length=500):
    sentences = text.split('. ')
    chunks = []
    current_chunk = ""
    
    for sentence in sentences:
        if len(current_chunk) + len(sentence) < max_length:
            current_chunk += sentence + ". "
        else:
            chunks.append(current_chunk.strip())
            current_chunk = sentence + ". "
    
    if current_chunk:
        chunks.append(current_chunk.strip())
    
    return chunks
```

## Use Appropriate Speech Speed

* **0.5x - 0.8x**: For clear, slow speech (accessibility, learning)
* **1.0x**: Normal speed (default, most use cases)
* **1.2x - 1.5x**: Fast speech (summaries, notifications)

`speed` changes `standard` voices only; `m1` voices ignore it.

## Implement Retry Logic

For production applications, implement exponential backoff:

```python
import time

def make_request_with_retry(url, headers, data, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = requests.post(url, headers=headers, json=data)
            if response.status_code == 200:
                return response
            elif response.status_code == 429:
                # Rate limited, wait and retry
                wait_time = 2 ** attempt
                time.sleep(wait_time)
                continue
            else:
                response.raise_for_status()
        except Exception as e:
            if attempt == max_retries - 1:
                raise
            wait_time = 2 ** attempt
            time.sleep(wait_time)
    return None
```

## Store API Keys Securely

Never commit API keys to version control:

```python
import os

API_KEY = os.environ.get('BAKBAK_API_KEY')
if not API_KEY:
    raise ValueError("BAKBAK_API_KEY environment variable not set")
```

## Monitor Usage

Track your API usage to stay within limits:

* Monitor request counts
* Track response times
* Log errors and failures
* Set up alerts for rate limits

## Test Different Voices

Test multiple voices to find the best fit:

* Different voices may work better for different content types
* Consider user preferences
* Test with actual content samples

## Handle Streaming Responses

For streaming endpoints, properly handle SSE format:

```python
import json
import base64

def handle_streaming_response(response):
    for line in response.iter_lines():
        if line.startswith(b'data: '):
            data = json.loads(line[6:])
            if data['type'] == 'chunk':
                # Decode base64 audio
                audio_data = base64.b64decode(data['data'])
                # Process audio chunk
                process_audio_chunk(audio_data)
            elif data['type'] == 'done':
                # Streaming complete
                break
```

## Performance Tips

1. **Batch requests** when possible for non-streaming
2. **Use connection pooling** for multiple requests
3. **Compress responses** when transferring over network
4. **Cache frequently used audio** locally
5. **Monitor latency** and optimize accordingly