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

# Text to Speech SDK

Generate natural-sounding speech from text with our SDKs. This guide will walk you through the essential steps to get started with text-to-speech synthesis in your applications.

## Prerequisites

Before you begin, make sure you have:

* An aiOla API key ([get one here](https://platform.aiola.ai/))
* Python 3.10+ (for Python SDK) or Node.js 18+ (for TypeScript SDK)

## Step 1: Install the SDK

#### Python

```bash
pip install aiola
```

#### TypeScript

```bash
npm install @aiola/sdk
# or
yarn add @aiola/sdk
```

## Step 2: Set up authentication

First, you'll need to generate an access token using your API key:

> **Info**
>
> For detailed authentication information, security best practices, and advanced token management, see our [Authentication Guide](../authentication).

#### Python

```python
from aiola import AiolaClient

# Generate access token
result = AiolaClient.grant_token(api_key='your-api-key')
access_token = result.access_token

# Create client
client = AiolaClient(access_token=access_token)
```

#### TypeScript

```typescript
import { AiolaClient } from '@aiola/sdk';

// Generate access token
const { accessToken } = await AiolaClient.grantToken({
  apiKey: 'your-api-key'
});

// Create client
const client = new AiolaClient({ accessToken });
```

## Step 3: Generate speech from text

Here's how to convert text to speech and save it as an audio file:

#### Python

```python
# Generate speech from text
text = "Hello, this is a sample text to speech conversion using aiOla SDK."

audio = client.tts.synthesize(
    text=text,
    voice='tara',  # Choose from available voices
    language='en'
)

# Save the audio to a file
with open('output.wav', 'wb') as f:
    for chunk in audio:
        f.write(chunk)

print("Audio file generated successfully!")
```

#### TypeScript

```typescript
// Generate speech from text
const text = "Hello, this is a sample text to speech conversion using aiOla SDK.";

const audio = await client.tts.synthesize({
  text: text,
  voice: 'tara',  // Choose from available voices
  language: 'en'
});

// Save the audio to a file (Node.js)
import fs from 'fs';

const fileStream = fs.createWriteStream('./output.wav');
for await (const chunk of audio) {
    fileStream.write(chunk);
}

console.log("Audio file generated successfully!");
```

## Real-time streaming

For real-time audio streaming, check out our dedicated [Text to Speech Streaming Guide](streaming) which covers:

* Streaming audio generation for immediate playback
* Chunk-based processing for low latency
* Node.js implementations

## Available voices

The following predefined voices are available: **tara**, **zoe**, **zac**, **dan**, **jess**, **leo**, **mia**, **julia**, and **leah**.

## Supported language

The SDK currently supports:

* **English** (`en`) - Primary language for text-to-speech synthesis

## Error handling

Always implement proper error handling for your API calls:

#### Python

```python
try:
    audio = client.tts.synthesize(
        text="Sample text for speech synthesis.",
        voice='jess',
        language='en'
    )
    
    with open("output.wav", "wb") as f:
        for chunk in audio:
            f.write(chunk)
        
    print("Speech synthesis completed successfully!")
    
except Exception as e:
    print(f"Speech synthesis failed: {e}")
```

#### TypeScript

```typescript
try {
  const audio = await client.tts.synthesize({
    text: "Sample text for speech synthesis.",
    voice: 'jess',
    language: 'en'
  });
  
  // Save the audio file
  import fs from 'fs';
  
  const fileStream = fs.createWriteStream('./output.wav');
  for await (const chunk of audio) {
      fileStream.write(chunk);
  }
  
  console.log("Speech synthesis completed successfully!");
  
} catch (error) {
  if (error instanceof Error) {
    console.error('Speech synthesis failed:', error.message);
  }
}
```

## Async operations (Python)

For asynchronous operations in Python:

#### Python

```python
from aiola import AsyncAiolaClient
import asyncio

async def async_tts_example():
    # Generate access token
    result = AsyncAiolaClient.grant_token(api_key='your-api-key')
    access_token = result.access_token
    
    # Create async client
    async_client = AsyncAiolaClient(access_token=access_token)
    
    # Generate speech asynchronously
    audio = await async_client.tts.synthesize(
        text="This is async text to speech.",
        voice='jess',
        language='en'
    )
    
    # Save audio
    with open("async_output.wav", "wb") as f:
        async for chunk in audio:
            f.write(chunk)

# Run the async function
asyncio.run(async_tts_example())
```

## Best practices

1. **Text Length**: Keep text reasonably short for optimal performance
2. **Error Handling**: Always implement try-catch blocks for API calls
3. **Resource Management**: Properly handle audio streams and file operations
4. **Audio Format Compatibility**: Ensure audio format compatibility across different environments
5. **Rate Limiting**: Be mindful of API rate limits for production applications

## Next steps

Now that you've successfully generated your first audio file, you can:

* Explore [TTS Streaming](streaming) for real-time speech synthesis
* Learn about [Speech to Text SDK](../speech-to-text/quickstart) for converting speech back to text
* Check out the SDK repositories for more examples:
  * [Python SDK](https://github.com/aiola-lab/aiola-python-sdk)
  * [TypeScript SDK](https://github.com/aiola-lab/aiola-js-sdk)