# Text to Speech
Source: https://typecast.ai/docs/api-reference/endpoint/text-to-speech/text-to-speech
POST /v1/text-to-speech
Generate speech from text using the specified voice model. Supports emotion, volume, pitch, and tempo customization.
First, list all available voice models using the GET /v1/voices endpoint, then use the voice_id from the response to generate speech with this endpoint. Each voice model has its own unique characteristics. See [Listing all voices](/docs/api-reference/endpoint/voices/voice) for available voices.
# Listing all voices
Source: https://typecast.ai/docs/api-reference/endpoint/voices/voice
GET /v1/voices
Lists all available voice models for text-to-speech conversion.
This endpoint returns a complete list of voices including each voice's ID, name, supported model type (ssfm-v21), and available emotion options (happy, sad, angry, normal, etc.).
Returned voices have unique identifiers starting with either 'tc_' prefix (Typecast voices) or 'uc_' prefix (User-created voices).
Optional query parameters can be used to filter results by specific model type.
# Get Voice by ID
Source: https://typecast.ai/docs/api-reference/endpoint/voices/voice-id
GET /v1/voices/{voice_id}
Get details of a specific voice model.
# AWS Marketplace
Source: https://typecast.ai/docs/bestpractice/aws-marketplace
Learn how to integrate Typecast SSFM with AWS Marketplace, a fully managed service that provides access to foundation models via API.
Get started with Typecast SSFM on AWS Marketplace in just a few steps:
Visit our [AWS Marketplace listing](https://aws.amazon.com/marketplace/seller-profile?id=seller-rauqp3qawr25s)
Click "Continue to Subscribe"
Review and accept the terms and conditions
Once subscribed, you can access Typecast SSFM through AWS API Gateway
Use your AWS credentials to authenticate API calls
Start generating high-quality speech with our state-of-the-art models
Deploy typecast ssfm Model Package from AWS Marketplace
Get started with Typecast SSFM on AWS Marketplace
# Prompting
Source: https://typecast.ai/docs/bestpractice/prompting
Learn how to maximize the potential of Typecast SSFM through various prompting techniques and discover advanced prompting strategies to enhance your text-to-speech outputs.
## Predefined style of speaking
\| `ssfm-v21`
Enhance your speech with preset emotional styles like `happy`, `sad`, or `angry`. You can customize how intense these emotions sound to get exactly the mood you want. These presets make it easy to add natural-sounding emotions to your text-to-speech output.
```bash cURL theme={null}
curl -N -X POST "https://api.typecast.ai/v1/text-to-speech" \
-H "X-API-KEY: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "ssfm-v21",
"voice_id": "tc_62a8975e695ad26f7fb514d1",
"text": "Hello there! I am your friendly text-to-speech agent.",
"prompt": {
"preset": "happy",
"preset_intensity": 2.0
}
}' > typecast.wav
```
```python Python theme={null}
import requests
import os
api_key = os.environ.get("TYPECAST_API_KEY", "YOUR_API_KEY")
url = "https://api.typecast.ai/v1/text-to-speech"
headers = {"X-API-KEY": api_key, "Content-Type": "application/json"}
payload = {
"model": "ssfm-v21",
"voice_id": "tc_62a8975e695ad26f7fb514d1",
"text": "Hello there! I am your friendly text-to-speech agent.",
"prompt": {
"preset": "happy",
"preset_intensity": 2.0
}
}
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
with open('typecast.wav', 'wb') as f:
f.write(response.content)
print("Audio file saved as typecast.wav")
else:
print(f"Error: {response.status_code} - {response.text}")
```
```javascript Javascript theme={null}
import fs from 'fs';
const apiKey = process.env.TYPECAST_API_KEY || 'YOUR_API_KEY';
async function convertTextToSpeech() {
const url = 'https://api.typecast.ai/v1/text-to-speech';
const payload = {
model: "ssfm-v21",
voice_id: "tc_62a8975e695ad26f7fb514d1",
text: "Hello there! I am your friendly text-to-speech agent.",
prompt: {
preset: "happy",
preset_intensity: 2.0
}
};
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'X-API-KEY': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`Error: ${response.status} - ${await response.text()}`);
}
const audioData = await response.arrayBuffer();
fs.writeFileSync('typecast.wav', Buffer.from(audioData));
console.log('Audio file saved as typecast.wav');
} catch (error) {
console.error('Error converting text to speech:', error);
}
}
convertTextToSpeech();
```
# Models
Source: https://typecast.ai/docs/models
## About our foundation model SSFM
Typecast currently uses an advanced AI voice model, the Typecast Speech Synthesis Foundation Model, or Typecast SSFM for short, which is our next generation text-to-speech technology that brings text to life with unparalleled naturalness and expressiveness.
## Models overview
| Model | Release Date | Description |
| :-------------------- | :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `ssfm-v21` | 2025.04 |
Best quality
Multilingual(27 languages)
Exceptional naturalness and expressiveness
Powerful Controllability of emotions and speaking styles
|
## ssfm-v21
* Various emotions: `Neutral`, `Happy`, `Sad`, and `Angry`
* Speaking languages: English, Korean, Chinese, Spanish, Arabic, Portuguese, Russian, Japanese, German, French, Indonesian, Italian, Malay, Polish, Dutch, Ukrainian, Greek, Tamil, Swedish, Czech, Danish, Finnish, Tagalog, Slovak, Bulgarian, Croatian, Romanian
# Overview
Source: https://typecast.ai/docs/overview
Typecast is a text-to-speech API that allows you to convert text into lifelike speech.
Typecast is a text-to-speech(TTS) platform that enables users to create natural-sounding voiceovers using AI technology. The service provides a variety of synthetic voices and allows users to convert text into speech in multiple languages.
Typecast's API enables developers to integrate text-to-speech capabilities into their applications, offering features such as voice customization, multiple language support, and various voice styles. The platform supports both male and female voices across different age ranges and accents, making it suitable for various applications including e-learning content, video narration, audiobook production, and more.
The service uses advanced deep learning models to generate human-like speech patterns, including appropriate intonation and emotional expression. Developers can access these features through RESTful API endpoints, with support for both synchronous and asynchronous processing of text-to-speech requests.
The platform provides comprehensive documentation for integration, including code examples in multiple programming languages, and offers various subscription tiers to accommodate different usage needs.
Get started with Typecast and create your first AI voice.
Learn about the models we offer.
Learn how to use the Typecast API
# Quickstart
Source: https://typecast.ai/docs/quickstart
Get started with Typecast and create your first AI voice.
## Get Started with Authentication
To use the Typecast API, you'll need to authenticate your requests with an API key. Follow these steps:
Visit your [Typecast Dashboard](https://typecast.ai/developers) to generate a new API key
Keep your API key secure - we recommend storing it as an environment variable
## Make your first request
```bash Python theme={null}
pip install typecast-python
```
```bash JavaScript theme={null}
npm install @neosapience/typecast-js
```
```python Python theme={null}
from typecast.client import Typecast
from typecast.models import TTSRequest, Prompt
# Initialize client
cli = Typecast(api_key="YOUR_API_KEY")
# Convert text to speech
response = cli.text_to_speech(TTSRequest(
text="Hello there! I am your friendly text-to-speech agent.",
model="ssfm-v21",
voice_id="tc_62a8975e695ad26f7fb514d1",
prompt=Prompt(
emotion_preset="happy",
emotion_intensity=2.0
)
))
# Save audio file
with open('typecast.wav', 'wb') as f:
f.write(response.audio_data)
```
```javascript Javascript theme={null}
import { TypecastClient } from '@neosapience/typecast-js';
import fs from 'fs';
// Initialize client
const client = new TypecastClient({
apiKey: 'YOUR_API_KEY'
});
// Convert text to speech
const audio = await client.textToSpeech({
text: "Hello there! I am your friendly text-to-speech agent.",
model: "ssfm-v21",
voice_id: "tc_62a8975e695ad26f7fb514d1",
prompt: {
emotion_preset: "happy",
emotion_intensity: 2.0
}
});
// Save audio file
await fs.promises.writeFile('typecast.wav', Buffer.from(audio.audioData));
```
You can set up your API key in two ways:
* Configure it directly in your application code
* Set it as a shell environment variable
```bash Shell (Linux/macOS) theme={null}
# Set for current session
export TYPECAST_API_KEY='YOUR_API_KEY'
```
```bash Shell (Windows) theme={null}
# Set for current session
set TYPECAST_API_KEY=YOUR_API_KEY
```
```python Python theme={null}
import requests
import os
api_key = os.environ.get("TYPECAST_API_KEY", "YOUR_API_KEY")
url = "https://api.typecast.ai/v1/text-to-speech"
headers = {"X-API-KEY": api_key, "Content-Type": "application/json"}
payload = {
"text": "Hello there! I am your friendly text-to-speech agent.",
"model": "ssfm-v21",
"voice_id": "tc_62a8975e695ad26f7fb514d1",
"prompt": {
"preset": "happy",
"preset_intensity": 2.0
}
}
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
with open('typecast.wav', 'wb') as f:
f.write(response.content)
print("Audio file saved as typecast.wav")
else:
print(f"Error: {response.status_code} - {response.text}")
```
```javascript Javascript theme={null}
import fs from "fs";
const apiKey = process.env.TYPECAST_API_KEY || 'YOUR_API_KEY';
async function convertTextToSpeech() {
const url = 'https://api.typecast.ai/v1/text-to-speech';
const payload = {
text: "Hello there! I am your friendly text-to-speech agent.",
model: "ssfm-v21",
voice_id: "tc_62a8975e695ad26f7fb514d1",
prompt: {
preset: "happy",
preset_intensity: 2.0
}
};
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'X-API-KEY': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`Error: ${response.status} - ${await response.text()}`);
}
const audioData = await response.arrayBuffer();
fs.writeFileSync('typecast.wav', Buffer.from(audioData));
console.log('Audio file saved as typecast.wav');
} catch (error) {
console.error('Error converting text to speech:', error);
}
}
convertTextToSpeech();
```
```bash cURL theme={null}
curl -N -X POST "https://api.typecast.ai/v1/text-to-speech" \
-H "X-API-KEY: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "ssfm-v21",
"text": "Hello there! I am your friendly text-to-speech agent.",
"voice_id": "tc_62a8975e695ad26f7fb514d1"
}' > typecast.wav
```
To browse and select available voice IDs for your requests, please refer to [Listing all voices](/api-reference/endpoint/voices/voice) in our API Reference.
## List all voices
To use Typecast effectively, you need access to voice IDs. The `/v1/voices` endpoint provides a complete list of available voices with their unique identifiers, names, models, and supported emotions.
You can also filter voices by model type using the optional `model` query parameter.
You can explore our complete voice catalog in more detail on the [Voices](/voices) page, where you'll find additional information about each voice's characteristics, sample audio clips, and recommended use cases.
```python Python theme={null}
from typecast.client import Typecast
# Initialize client
cli = Typecast(api_key="YOUR_API_KEY")
# Get all voices (optionally filter by model)
voices = cli.get_voices(model="ssfm-v21") # Optional parameter
print(f"Found {len(voices)} voices:")
for voice in voices:
print(f"ID: {voice.voice_id}, Name: {voice.voice_name}, Emotions: {', '.join(voice.emotions)}")
```
```javascript Javascript theme={null}
import { TypecastClient } from '@neosapience/typecast-js';
// Initialize client
const client = new TypecastClient({
apiKey: 'YOUR_API_KEY'
});
// Get all voices (optionally filter by model)
const voices = await client.getVoices({model: 'ssfm-v21'}); // Optional parameter
console.log(`Found ${voices.length} voices:`);
voices.forEach(voice => {
console.log(`ID: ${voice.voice_id}, Name: ${voice.voice_name}, Emotions: ${voice.emotions.join(', ')}`);
});
```
```python Python theme={null}
import requests
import os
api_key = os.environ.get("TYPECAST_API_KEY", "YOUR_API_KEY")
url = "https://api.typecast.ai/v1/voices"
headers = {"X-API-KEY": api_key}
params = {"model": "ssfm-v21"} # Optional
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
voices = response.json()
print(f"Found {len(voices)} voices:")
for voice in voices:
print(f"ID: {voice['voice_id']}, Name: {voice['voice_name']}, Emotions: {', '.join(voice['emotions'])}")
else:
print(f"Error: {response.status_code} - {response.text}")
```
```javascript Javascript theme={null}
const apiKey = process.env.TYPECAST_API_KEY || 'YOUR_API_KEY';
async function getVoices() {
const url = 'https://api.typecast.ai/v1/voices';
const params = new URLSearchParams({model: 'ssfm-v21'});
try {
const response = await fetch(`${url}?${params}`, {
method: 'GET',
headers: {'X-API-KEY': apiKey}
});
if (!response.ok) {
throw new Error(`Error: ${response.status} - ${await response.text()}`);
}
const voices = await response.json();
console.log(`Found ${voices.length} voices:`);
voices.forEach(voice => {
console.log(`ID: ${voice.voice_id}, Name: ${voice.voice_name}, Emotions: ${voice.emotions.join(', ')}`);
});
} catch (error) {
console.error('Error fetching voices:', error);
}
}
getVoices();
```
```bash cURL theme={null}
curl -X GET "https://api.typecast.ai/v1/voices?model=ssfm-v21" \
-H "X-API-KEY: YOUR_API_KEY" \
-H "Content-Type: application/json"
```
The response will be a JSON array of voice objects, each containing:
```json theme={null}
{
"voice_id": "tc_62a8975e695ad26f7fb514d1",
"voice_name": "Olivia",
"model": "ssfm-v21",
"emotions": ["tonemid", "toneup", "normal", "happy", "sad", "angry"]
}
```
You'll need a valid voice ID when making text-to-speech requests. Make sure to select a voice that supports your desired emotion for the best results.
## Next steps
Congratulations on creating your first AI voice! Here are some resources to help you dive deeper:
Learn how to use the Typecast API
Learn about the models we offer.
Typecast has 530+ unique voices to choose from
# Javascript/Typescript
Source: https://typecast.ai/docs/sdk/javascript
Access the Typecast API with our official Javascript/Typescript SDK.
The official Node.js library for the [Typecast API](https://typecast.ai). Convert text to lifelike speech using AI-powered voices.
Works with both JavaScript and TypeScript. Full TypeScript types included.
ESM & CommonJS supported. This SDK targets Node.js environments only (browser usage is not supported).
Typecast Javascript/Typescript SDK
Typecast Javascript/Typescript SDK Source Code
## Installation
```bash theme={null}
npm install @neosapience/typecast-js
```
## Quick Start
```typescript theme={null}
import { TypecastClient } from '@neosapience/typecast-js';
import fs from 'fs';
async function main() {
const client = new TypecastClient({ apiKey: 'YOUR_API_KEY' });
const audio = await client.textToSpeech({
text: "Hello there! I'm your friendly text-to-speech agent.",
model: "ssfm-v21",
voice_id: "tc_62a8975e695ad26f7fb514d1"
});
await fs.promises.writeFile(`output.${audio.format}`, Buffer.from(audio.audioData));
console.log(`Audio saved! Duration: ${audio.duration}s, Format: ${audio.format}`);
}
main();
```
```javascript theme={null}
const { TypecastClient } = require('@neosapience/typecast-js');
const fs = require('fs');
async function main() {
const client = new TypecastClient({ apiKey: 'YOUR_API_KEY' });
const audio = await client.textToSpeech({
text: "Hello there! I'm your friendly text-to-speech agent.",
model: "ssfm-v21",
voice_id: "tc_62a8975e695ad26f7fb514d1"
});
await fs.promises.writeFile(`output.${audio.format}`, Buffer.from(audio.audioData));
console.log(`Audio saved! Duration: ${audio.duration}s, Format: ${audio.format}`);
}
main();
```
## Features
The Typecast JavaScript/TypeScript SDK provides powerful features for text-to-speech conversion:
* ποΈ **Multiple Voice Models**: Support for AI voice models with natural speech synthesis
* π **Multi-language Support**: 27+ languages including English, Korean, Spanish, Japanese, Chinese, and more
* π **Emotion Control**: Adjust emotional expression (happy, sad, angry, normal, tonemid, toneup) with intensity control
* ποΈ **Audio Customization**: Control volume (0-200), pitch (-12 to +12 semitones), tempo (0.5x to 2.0x), and format (WAV/MP3)
* π **Voice Discovery**: List and search available voices by model
* π **TypeScript Support**: Full type definitions included
## Configuration
Set your API key via environment variable or constructor:
```typescript theme={null}
// Using environment variable
// export TYPECAST_API_KEY="your-api-key-here"
const client = new TypecastClient({
apiKey: process.env.TYPECAST_API_KEY!
});
// Or pass directly
const client = new TypecastClient({
apiKey: 'your-api-key-here'
});
```
## Advanced Usage
### Emotion and Audio Control
Control emotion, volume, pitch, tempo, and output format:
```typescript theme={null}
const audio = await client.textToSpeech({
text: "I am so excited to show you these features!",
voice_id: "tc_62a8975e695ad26f7fb514d1",
model: "ssfm-v21",
language: "eng",
prompt: {
emotion_preset: "happy", // Options: normal, happy, sad, angry, tonemid, toneup
emotion_intensity: 1.5 // Range: 0.0 to 2.0
},
output: {
volume: 120, // Range: 0 to 200
audio_pitch: 2, // Range: -12 to +12 semitones
audio_tempo: 1.2, // Range: 0.5x to 2.0x
audio_format: "mp3" // Options: wav, mp3
},
seed: 42 // For reproducible results
});
await fs.promises.writeFile(`output.${audio.format}`, Buffer.from(audio.audioData));
console.log(`Duration: ${audio.duration}s, Format: ${audio.format}`);
```
### Voice Discovery
List and search available voices:
```typescript theme={null}
// List all voices
const voices = await client.getVoices();
// Filter by model
const v21Voices = await client.getVoices("ssfm-v21");
// Get specific voice
const voiceInfo = await client.getVoiceById("tc_62a8975e695ad26f7fb514d1");
console.log(`Voice: ${voiceInfo[0].voice_name}`);
console.log(`Available emotions: ${voiceInfo[0].emotions.join(', ')}`);
```
### Multilingual Content
The SDK supports 27+ languages with automatic language detection:
```typescript theme={null}
// Auto-detect language (recommended)
const audio = await client.textToSpeech({
text: "γγγ«γ‘γ―γγε ζ°γ§γγγ",
voice_id: "tc_62a8975e695ad26f7fb514d1",
model: "ssfm-v21"
});
// Or specify language explicitly
const koreanAudio = await client.textToSpeech({
text: "μλ νμΈμ. λ°κ°μ΅λλ€.",
voice_id: "tc_62a8975e695ad26f7fb514d1",
model: "ssfm-v21",
language: "kor" // ISO 639-3 language code
});
await fs.promises.writeFile(`output.${audio.format}`, Buffer.from(audio.audioData));
```
## Supported Languages
The SDK supports 27 languages with automatic language detection:
| Code | Language | Code | Language | Code | Language |
| ----- | -------- | ----- | -------- | ----- | ---------- |
| `eng` | English | `jpn` | Japanese | `ukr` | Ukrainian |
| `kor` | Korean | `ell` | Greek | `ind` | Indonesian |
| `spa` | Spanish | `tam` | Tamil | `dan` | Danish |
| `deu` | German | `tgl` | Tagalog | `swe` | Swedish |
| `fra` | French | `fin` | Finnish | `msa` | Malay |
| `ita` | Italian | `zho` | Chinese | `ces` | Czech |
| `pol` | Polish | `slk` | Slovak | `por` | Portuguese |
| `nld` | Dutch | `ara` | Arabic | `bul` | Bulgarian |
| `rus` | Russian | `hrv` | Croatian | `ron` | Romanian |
If not specified, the language will be automatically detected from the input text.
## Error Handling
The SDK provides `TypecastAPIError` for handling API errors:
```typescript theme={null}
import { TypecastClient, TypecastAPIError } from '@neosapience/typecast-js';
try {
const audio = await client.textToSpeech({
text: "Hello world",
voice_id: "tc_62a8975e695ad26f7fb514d1",
model: "ssfm-v21"
});
} catch (error) {
if (error instanceof TypecastAPIError) {
// TypecastAPIError exposes: statusCode, message, response
switch (error.statusCode) {
case 401:
console.error('Invalid API key');
break;
case 402:
console.error('Insufficient credits');
break;
case 422:
console.error('Validation error:', error.response);
break;
default:
console.error(`API error (${error.statusCode}):`, error.message);
}
} else {
console.error('Unexpected error:', error);
}
}
```
## TypeScript Support
This SDK is written in TypeScript and provides full type definitions:
```typescript theme={null}
import type {
TTSRequest,
TTSResponse,
LanguageCode,
Prompt,
Output
} from '@neosapience/typecast-js';
```
# Python
Source: https://typecast.ai/docs/sdk/python
Access the Typecast API with our official Python SDK.
Typecast Python SDK
Typecast Python SDK Source Code
## Installation
Install the Typecast Python SDK using pip:
```bash theme={null}
pip install typecast-python
```
The package is installed as `typecast-python`, but imported as `typecast`.
## Quick Start
Here's a simple example to convert text to speech:
```python theme={null}
from typecast.client import Typecast
from typecast.models import TTSRequest, Output
# Initialize client
cli = Typecast(api_key="YOUR_API_KEY")
# Convert text to speech
response = cli.text_to_speech(TTSRequest(
text="Hello there! I'm your friendly text-to-speech agent.",
model="ssfm-v21",
voice_id="tc_62a8975e695ad26f7fb514d1",
output=Output(audio_format="wav")
))
# Save audio file
with open('output.wav', 'wb') as f:
f.write(response.audio_data)
print(f"Duration: {response.duration}s, Format: {response.format}")
```
## Features
The Typecast Python SDK provides powerful features for text-to-speech conversion:
* ποΈ **Multiple Voice Models**: Support for various AI voice models (ssfm-v21, v20, etc.)
* π **Multi-language Support**: 27 languages including English, Korean, Spanish, Japanese, Chinese, and more
* π **Emotion Control**: Adjust emotional expression (happy, sad, angry, normal) with intensity control
* ποΈ **Audio Customization**: Control volume, pitch, tempo, and output format (WAV/MP3)
* β‘ **Async Support**: Built-in async client for high-performance applications
* π **Voice Discovery**: List and search available voices by model
## Configuration
You can configure the API key using environment variables or pass it directly to the client:
```bash Environment Variable theme={null}
export TYPECAST_API_KEY="your-api-key-here"
```
```python From Environment theme={null}
# From environment variable
cli = Typecast()
```
```python Direct Configuration theme={null}
# Or pass directly
cli = Typecast(api_key="your-api-key-here")
```
## Advanced Usage
### Emotion and Audio Control
Control emotions, pitch, tempo, and other audio parameters:
```python theme={null}
from typecast.client import Typecast
from typecast.models import TTSRequest, Prompt, Output, LanguageCode
cli = Typecast()
response = cli.text_to_speech(TTSRequest(
text="I am so excited to show you these features!",
model="ssfm-v21",
voice_id="tc_62a8975e695ad26f7fb514d1",
language=LanguageCode.ENG,
prompt=Prompt(
emotion_preset="happy", # Options: normal, happy, sad, angry
emotion_intensity=1.5 # Range: 0.0 to 2.0
),
output=Output(
volume=120, # Range: 0 to 200
audio_pitch=2, # Range: -12 to +12 semitones
audio_tempo=1.2, # Range: 0.5x to 2.0x
audio_format="mp3" # Options: wav, mp3
),
seed=42 # For reproducible results
))
```
### Voice Discovery
List and filter available voices:
```python theme={null}
# List all voices
voices = cli.voices()
# Filter by model
v21_voices = cli.voices(model="ssfm-v21")
# Get specific voice
voice = cli.get_voice("tc_62a8975e695ad26f7fb514d1")
print(f"Voice: {voice.voice_name}")
print(f"Available emotions: {voice.emotions}")
# Common voice fields: voice_id, voice_name, emotions, languages, models, gender, age_range
```
### Async Client
For high-performance applications, use the async client:
```python theme={null}
import asyncio
from typecast.async_client import AsyncTypecast
from typecast.models import TTSRequest, LanguageCode, Output
async def main():
async with AsyncTypecast() as cli:
response = await cli.text_to_speech(TTSRequest(
text="Hello from async!",
model="ssfm-v21",
voice_id="tc_62a8975e695ad26f7fb514d1",
language=LanguageCode.ENG,
output=Output(audio_format="wav")
))
with open('async_output.wav', 'wb') as f:
f.write(response.audio_data)
asyncio.run(main())
```
## Supported Languages
**Recommended**: Use the `LanguageCode` enum for type-safe language selection. You can also pass the ISO 639-3 code as a string (e.g., `"eng"`).
The SDK supports 27 languages with ISO 639-3 codes:
| Language | Code | Language | Code | Language | Code |
| -------- | ----- | -------- | ----- | ---------- | ----- |
| English | `eng` | Japanese | `jpn` | Ukrainian | `ukr` |
| Korean | `kor` | Greek | `ell` | Indonesian | `ind` |
| Spanish | `spa` | Tamil | `tam` | Danish | `dan` |
| German | `deu` | Tagalog | `tgl` | Swedish | `swe` |
| French | `fra` | Finnish | `fin` | Malay | `msa` |
| Italian | `ita` | Chinese | `zho` | Czech | `ces` |
| Polish | `pol` | Slovak | `slk` | Portuguese | `por` |
| Dutch | `nld` | Arabic | `ara` | Bulgarian | `bul` |
| Russian | `rus` | Croatian | `hrv` | Romanian | `ron` |
Use the `LanguageCode` enum for type-safe language selection:
```python theme={null}
from typecast.models import LanguageCode
request = TTSRequest(
text="Hello",
language=LanguageCode.ENG,
...
)
```
## Error Handling
The SDK provides specific exceptions for different HTTP status codes:
```python theme={null}
from typecast.exceptions import (
BadRequestError, # 400
UnauthorizedError, # 401
PaymentRequiredError, # 402
NotFoundError, # 404
UnprocessableEntityError, # 422
InternalServerError, # 500
TypecastError # Base exception
)
# All SDK exceptions have status_code and message attributes
try:
response = cli.text_to_speech(request)
except UnauthorizedError:
print("Invalid API key")
except PaymentRequiredError:
print("Insufficient credits")
except TypecastError as e:
print(f"Error: {e.message}, Status: {e.status_code}")
```