# Speechgen
> Advanced AI-powered speech generation and text-to-speech platform.
[Canonical source](https://www.speechgen.app/)
## Text-to-speech
Enter text, choose a voice and language, then generate a speech sample and listen to it on the homepage.
## Voice cloning
Upload a voice sample or record one with your microphone. Use recordings you own or have permission to use.
## Explore Speechgen
- [Pricing](https://www.speechgen.app/pricing): Compare Speechgen plans.
- [Use cases](https://www.speechgen.app/use-cases): Find text-to-speech tools for different workflows.
- [Voice types](https://www.speechgen.app/voices): Explore narration, character, and other voice types.
- [Languages](https://www.speechgen.app/languages): Explore text-to-speech options by language.
- [Tools](https://www.speechgen.app/tools): Find readers, narrators, and other speech tools.
- [Accessibility](https://www.speechgen.app/accessibility): Explore ways text-to-speech can support accessibility.
- [Provider comparisons](https://www.speechgen.app/companies): Compare text-to-speech providers.
- [API documentation](https://www.speechgen.app/api-docs)
---
# Authentication
[Canonical source](https://www.speechgen.app/api-docs/authentication)
Learn how to authenticate your API requests
# Authentication
All API requests require authentication using a Bearer token. Your API key identifies your account and determines your rate limits and permissions.
## Getting Your API Key
1. Sign up for a [Speechgen account](https://speechgen.app/signup)
2. Navigate to your [Dashboard](https://speechgen.app/dashboard)
3. Click on "API Keys" in the sidebar
4. Click "Generate New Key"
5. Copy and securely store your API key
**Security Warning**: Never expose your API key in client-side code or public
repositories. Always use environment variables or secure key management
systems.
## Using Your API Key
Include your API key in the `Authorization` header of every request:
```http
Authorization: Bearer YOUR_API_KEY
```
### Example Request
```bash
curl -X GET https://api.speechgen.com/v1/voices \
-H "Authorization: Bearer sk_live_abc123xyz..."
```
## API Key Types
| Type | Prefix | Use Case |
| ---- | ---------- | ----------------------- |
| Live | `sk_live_` | Production applications |
| Test | `sk_test_` | Development and testing |
Test keys have reduced rate limits but don't count against your monthly usage
quota.
## Error Responses
### Invalid API Key
```json
{
"error": {
"code": "invalid_api_key",
"message": "The API key provided is invalid or has been revoked."
}
}
```
### Missing API Key
```json
{
"error": {
"code": "missing_api_key",
"message": "No API key was provided. Include your key in the Authorization header."
}
}
```
## Best Practices
1. **Rotate keys regularly**: Generate new keys periodically and revoke old ones
2. **Use environment variables**: Store keys in `SPEECHGEN_API_KEY` environment variable
3. **Monitor usage**: Check your dashboard for unusual activity
4. **Set up alerts**: Configure notifications for rate limit warnings
```bash
# Store in environment variable
export SPEECHGEN_API_KEY="sk_live_your_key_here"
```
```javascript
// Access in Node.js
const apiKey = process.env.SPEECHGEN_API_KEY;
```
## Frequently Asked Questions
Yes, you can generate multiple API keys for different applications or
environments. Each key can be individually revoked without affecting others.
This is useful for separating development, staging, and production
environments.
If you suspect your API key has been compromised, immediately revoke it from
your dashboard and generate a new one. You can view recent API activity in
your dashboard to check for unauthorized usage.
API keys do not expire automatically. However, we recommend rotating your
keys periodically (e.g., every 90 days) as a security best practice.
Currently, API keys have full access to all endpoints. We're working on
scoped API keys that will allow you to restrict permissions. Join our
newsletter for updates.
When you exceed your rate limit, the API returns a 429 status code.
Implement exponential backoff in your code to handle this gracefully. Check
the `X-RateLimit-Reset` header to know when you can retry.
---
# API Endpoints
[Canonical source](https://www.speechgen.app/api-docs/endpoints)
Complete reference of all available API endpoints
# API Endpoints
All endpoints are relative to the base URL: `https://api.speechgen.com/v1`
## Overview
| Method | Endpoint | Description |
| -------- | ----------------- | ------------------------------- |
| `POST` | `/text-to-speech` | Convert text to speech |
| `POST` | `/voice-clone` | Create a voice clone from audio |
| `GET` | `/voices` | List all available voices |
| `GET` | `/voices/{id}` | Get voice details |
| `GET` | `/audio/{id}` | Retrieve generated audio |
| `GET` | `/models` | List your voice models |
| `DELETE` | `/models/{id}` | Delete a voice model |
## Text-to-Speech
Convert text to natural-sounding speech.
```http
POST /text-to-speech
```
**Request Body:**
```json
{
"text": "Hello, welcome to Speechgen!",
"voice": "en-US-Neural2-A",
"format": "mp3",
"speed": 1.0,
"pitch": 0
}
```
**Response:** Binary audio data
[View full documentation →](/api-docs/text-to-speech)
***
## Voice Clone
Create a custom voice model from audio samples.
```http
POST /voice-clone
Content-Type: multipart/form-data
```
**Form Data:**
**Response:**
```json
{
"model_id": "vm_abc123",
"status": "processing",
"estimated_time": 60
}
```
[View full documentation →](/api-docs/voice-clone)
***
## List Voices
Get all available voices.
```http
GET /voices
```
**Query Parameters:**
**Response:**
```json
{
"voices": [
{
"id": "en-US-Neural2-A",
"name": "Aria",
"language": "en-US",
"gender": "female",
"styles": ["cheerful", "professional", "calm"]
}
]
}
```
[View full documentation →](/api-docs/voices)
***
## Retrieve Audio
Download a previously generated audio file.
```http
GET /audio/{id}
```
**Response:** Binary audio data
Audio files are stored for 7 days. Download and store them if you need longer
retention.
***
## HTTP Status Codes
\| Code | Description | |------|-------------| | `200` | Success - Request
completed successfully | | `201` | Created - Resource was successfully
created | | `204` | No Content - Request succeeded with no response body |
\| Code | Description | |------|-------------| | `400` | Bad Request -
Invalid parameters or malformed request | | `401` | Unauthorized - Invalid
or missing API key | | `403` | Forbidden - Insufficient permissions for this
action | | `404` | Not Found - The requested resource doesn't exist | |
`429` | Too Many Requests - Rate limit exceeded, retry later |
\| Code | Description | |------|-------------| | `500` | Internal Server
Error - Something went wrong on our end | | `502` | Bad Gateway - Service
temporarily unavailable | | `503` | Service Unavailable - Server is
overloaded or under maintenance |
---
# Code Examples
[Canonical source](https://www.speechgen.app/api-docs/examples)
Complete code examples for common use cases
# Code Examples
Complete, copy-paste ready examples for integrating Speechgen into your applications.
## Basic Text-to-Speech
```javascript
const SPEECHGEN_API_KEY = process.env.SPEECHGEN_API_KEY;
async function textToSpeech(text, voice = 'en-US-Neural2-A') {
const response = await fetch('https://api.speechgen.com/v1/text-to-speech', {
method: 'POST',
headers: {
'Authorization': `Bearer ${SPEECHGEN_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
text,
voice,
format: 'mp3',
}),
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return response.blob();
}
// Usage
const audioBlob = await textToSpeech('Hello, world!');
```
```python
import os
import requests
SPEECHGEN_API_KEY = os.environ['SPEECHGEN_API_KEY']
def text_to_speech(text: str, voice: str = 'en-US-Neural2-A') -> bytes:
response = requests.post(
'https://api.speechgen.com/v1/text-to-speech',
headers={
'Authorization': f'Bearer {SPEECHGEN_API_KEY}',
'Content-Type': 'application/json',
},
json={
'text': text,
'voice': voice,
'format': 'mp3',
}
)
response.raise_for_status()
return response.content
# Usage
audio = text_to_speech('Hello, world!')
with open('output.mp3', 'wb') as f:
f.write(audio)
```
```bash
curl -X POST https://api.speechgen.com/v1/text-to-speech \
-H "Authorization: Bearer $SPEECHGEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Hello, world!",
"voice": "en-US-Neural2-A",
"format": "mp3"
}' \
--output output.mp3
```
## React Integration
### Project Structure
### Audio Player Component
```tsx
import { useState, useRef } from "react";
interface TTSPlayerProps {
text: string;
voice?: string;
}
export function TTSPlayer({ text, voice = "en-US-Neural2-A" }: TTSPlayerProps) {
const [isLoading, setIsLoading] = useState(false);
const [audioUrl, setAudioUrl] = useState(null);
const audioRef = useRef(null);
const generateSpeech = async () => {
setIsLoading(true);
try {
const response = await fetch("/api/tts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text, voice }),
});
const blob = await response.blob();
const url = URL.createObjectURL(blob);
setAudioUrl(url);
// Auto-play
if (audioRef.current) {
audioRef.current.play();
}
} catch (error) {
console.error("TTS Error:", error);
} finally {
setIsLoading(false);
}
};
return (
{audioUrl && }
);
}
```
### Next.js API Route
```typescript
// app/api/tts/route.ts
import { NextRequest, NextResponse } from "next/server";
export async function POST(request: NextRequest) {
const { text, voice } = await request.json();
const response = await fetch("https://api.speechgen.com/v1/text-to-speech", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SPEECHGEN_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ text, voice, format: "mp3" }),
});
if (!response.ok) {
return NextResponse.json(
{ error: "Failed to generate speech" },
{ status: response.status }
);
}
const audioBuffer = await response.arrayBuffer();
return new NextResponse(audioBuffer, {
headers: {
"Content-Type": "audio/mpeg",
},
});
}
```
## Node.js Server
### Project Structure
### Express.js Integration
```javascript
const express = require("express");
const fetch = require("node-fetch");
const app = express();
app.use(express.json());
app.post("/api/tts", async (req, res) => {
const { text, voice } = req.body;
try {
const response = await fetch(
"https://api.speechgen.com/v1/text-to-speech",
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SPEECHGEN_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
text,
voice: voice || "en-US-Neural2-A",
format: "mp3",
}),
}
);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const buffer = await response.buffer();
res.set("Content-Type", "audio/mpeg");
res.send(buffer);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
```
## Batch Processing
### Process Multiple Texts
```python
import asyncio
import aiohttp
import os
SPEECHGEN_API_KEY = os.environ['SPEECHGEN_API_KEY']
async def generate_speech(session, text, voice, output_path):
async with session.post(
'https://api.speechgen.com/v1/text-to-speech',
headers={
'Authorization': f'Bearer {SPEECHGEN_API_KEY}',
'Content-Type': 'application/json',
},
json={
'text': text,
'voice': voice,
'format': 'mp3',
}
) as response:
if response.status == 200:
content = await response.read()
with open(output_path, 'wb') as f:
f.write(content)
return output_path
else:
raise Exception(f'Error: {response.status}')
async def batch_process(texts, voice='en-US-Neural2-A'):
async with aiohttp.ClientSession() as session:
tasks = [
generate_speech(session, text, voice, f'output_{i}.mp3')
for i, text in enumerate(texts)
]
return await asyncio.gather(*tasks)
# Usage
texts = [
"Welcome to chapter one.",
"This is chapter two.",
"And finally, chapter three.",
]
asyncio.run(batch_process(texts))
```
## Voice Cloning Workflow
### Complete Clone and Use Example
```javascript
const fs = require("fs");
const FormData = require("form-data");
const fetch = require("node-fetch");
const API_KEY = process.env.SPEECHGEN_API_KEY;
const BASE_URL = "https://api.speechgen.com/v1";
// Step 1: Clone a voice
async function cloneVoice(audioPath, name) {
const formData = new FormData();
formData.append("audio", fs.createReadStream(audioPath));
formData.append("name", name);
formData.append("enhance_quality", "true");
const response = await fetch(`${BASE_URL}/voice-clone`, {
method: "POST",
headers: {
Authorization: `Bearer ${API_KEY}`,
},
body: formData,
});
return response.json();
}
// Step 2: Wait for processing
async function waitForModel(modelId) {
while (true) {
const response = await fetch(`${BASE_URL}/models/${modelId}`, {
headers: { Authorization: `Bearer ${API_KEY}` },
});
const model = await response.json();
if (model.status === "ready") return model;
if (model.status === "failed") throw new Error("Cloning failed");
await new Promise((r) => setTimeout(r, 5000));
}
}
// Step 3: Use the cloned voice
async function useClonedVoice(voiceId, text) {
const response = await fetch(`${BASE_URL}/text-to-speech`, {
method: "POST",
headers: {
Authorization: `Bearer ${API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
text,
voice: voiceId,
format: "mp3",
}),
});
return response.buffer();
}
// Complete workflow
async function main() {
console.log("Cloning voice...");
const clone = await cloneVoice("./my-voice-sample.mp3", "My Voice");
console.log("Waiting for processing...");
const model = await waitForModel(clone.model_id);
console.log("Generating speech with cloned voice...");
const audio = await useClonedVoice(
model.voice_id,
"Hello from my cloned voice!"
);
fs.writeFileSync("cloned-output.mp3", audio);
console.log("Done! Audio saved to cloned-output.mp3");
}
main().catch(console.error);
```
Need help with a specific integration? [Contact our support team](/contact) or
check our [Discord community](https://discord.gg/speechgen).
---
# API Documentation
[Canonical source](https://www.speechgen.app/api-docs)
Integrate powerful AI voice generation into your applications with our simple REST API.
# Welcome to Speechgen API
Integrate powerful AI voice generation into your applications with our simple REST API. Convert text to natural-sounding speech, clone voices, and access a library of premium AI voices.
}>
Get up and running in under 5 minutes
}>
Learn how to authenticate your API requests
}>
Convert text to natural speech
}>
Create custom voice clones
## Features
* **Text-to-Speech**: Convert any text to natural-sounding audio in multiple languages
* **Voice Cloning**: Create custom voice models from audio samples
* **100+ Premium Voices**: Access our library of AI-generated voices
* **Multiple Formats**: Export audio in MP3, WAV, or OGG formats
* **Low Latency**: Fast response times for real-time applications
## API Base URL
```
https://api.speechgen.com/v1
```
## Rate Limits
| Plan | Requests/min | Characters/month |
| ---------- | ------------ | ---------------- |
| Free | 10 | 10,000 |
| Pro | 60 | 500,000 |
| Enterprise | Unlimited | Unlimited |
Need higher limits? [Contact us](/contact) for enterprise pricing.
## Frequently Asked Questions
We support MP3, WAV, and OGG formats. MP3 is recommended for web
applications due to its smaller file size, while WAV is ideal for
professional audio editing.
Each request can convert up to 5,000 characters. For longer content, we
recommend splitting the text into multiple requests.
Yes, cloned voices can be used commercially. However, you must have the
rights to clone the voice (consent from the voice owner) and comply with our
terms of service.
We support 13+ languages including English (US/UK), Spanish, French, German,
Italian, Portuguese, Japanese, Korean, Chinese, Arabic, and Hindi. Check the
Voices API for a complete list.
---
# Quick Start
[Canonical source](https://www.speechgen.app/api-docs/quickstart)
Get up and running with the Speechgen API in under 5 minutes
# Quick Start Guide
Get started with the Speechgen API in just a few steps.
### Get your API key
Sign up for a Speechgen account and navigate to your [Dashboard](https://speechgen.app/dashboard) to generate your API key.
### Make your first request
Use the code examples below to convert text to speech.
### Handle the response
Receive audio data in your preferred format (MP3, WAV, OGG).
## Your First API Call
Here's a simple example to convert text to speech:
### cURL
```bash
curl -X POST https://api.speechgen.com/v1/text-to-speech \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Hello, welcome to Speechgen!",
"voice": "en-US-Neural2-A",
"format": "mp3"
}'
```
### JavaScript
```javascript
const response = await fetch("https://api.speechgen.com/v1/text-to-speech", {
method: "POST",
headers: {
Authorization: "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
},
body: JSON.stringify({
text: "Hello, welcome to Speechgen!",
voice: "en-US-Neural2-A",
format: "mp3",
}),
});
const audioBlob = await response.blob();
```
### Python
```python
import requests
response = requests.post(
'https://api.speechgen.com/v1/text-to-speech',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json',
},
json={
'text': 'Hello, welcome to Speechgen!',
'voice': 'en-US-Neural2-A',
'format': 'mp3',
}
)
audio_content = response.content
```
Remember to replace `YOUR_API_KEY` with your actual API key from the
dashboard.
## Recommended Project Structure
Here's a recommended structure for integrating Speechgen into your project:
* `lib/speechgen.ts` - Your Speechgen API client wrapper
* `app/api/tts/route.ts` - Server-side API route to proxy requests
* `.env.local` - Store your `SPEECHGEN_API_KEY` here
## Next Steps
* Learn about [Authentication](/api-docs/authentication)
* Explore all [API Endpoints](/api-docs/endpoints)
* Check out more [Code Examples](/api-docs/examples)
---
# Text to Speech
[Canonical source](https://www.speechgen.app/api-docs/text-to-speech)
Convert text to natural-sounding speech with our TTS API
# Text to Speech API
Convert any text into natural-sounding speech using our advanced neural TTS models.
## Endpoint
```http
POST https://api.speechgen.com/v1/text-to-speech
```
## Request
### Headers
| Header | Value | Required |
| --------------- | --------------------- | -------- |
| `Authorization` | `Bearer YOUR_API_KEY` | Yes |
| `Content-Type` | `application/json` | Yes |
### Body Parameters
### Example Request
```bash
curl -X POST https://api.speechgen.com/v1/text-to-speech \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Welcome to Speechgen. This is a demonstration of our text-to-speech capabilities.",
"voice": "en-US-Neural2-A",
"format": "mp3",
"speed": 1.0,
"pitch": 0
}'
```
## Response
### Success (200)
Returns binary audio data with appropriate content type:
* `audio/mpeg` for MP3
* `audio/wav` for WAV
* `audio/ogg` for OGG
**Response Headers:**
```http
Content-Type: audio/mpeg
Content-Length: 45678
X-Audio-Duration: 4.5
X-Characters-Used: 87
```
### Error Response
```json
{
"error": {
"code": "invalid_voice",
"message": "The specified voice 'invalid-voice' does not exist.",
"param": "voice"
}
}
```
## SSML Support
Our API supports Speech Synthesis Markup Language (SSML) for advanced control:
```json
{
"text": "Hello, welcome to Speechgen!",
"voice": "en-US-Neural2-A",
"format": "mp3"
}
```
### Supported SSML Tags
| Tag | Description | Example |
| ------------ | --------------------------- | ------------------------------------------------- |
| `` | Root element | `Hello` |
| `` | Insert pause | `` |
| `` | Control rate, pitch, volume | `...` |
| `` | Add emphasis | `...` |
| `` | Interpret text type | `2024-01-15` |
SSML text counts towards your character limit including the tags.
## Code Examples
### JavaScript/TypeScript
```typescript
async function textToSpeech(text: string, voice: string): Promise {
const response = await fetch("https://api.speechgen.com/v1/text-to-speech", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SPEECHGEN_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
text,
voice,
format: "mp3",
}),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error.message);
}
return response.blob();
}
// Usage
const audio = await textToSpeech("Hello world!", "en-US-Neural2-A");
```
### Python
```python
import requests
def text_to_speech(text: str, voice: str) -> bytes:
response = requests.post(
'https://api.speechgen.com/v1/text-to-speech',
headers={
'Authorization': f'Bearer {os.environ["SPEECHGEN_API_KEY"]}',
'Content-Type': 'application/json',
},
json={
'text': text,
'voice': voice,
'format': 'mp3',
}
)
response.raise_for_status()
return response.content
# Usage
audio = text_to_speech('Hello world!', 'en-US-Neural2-A')
with open('output.mp3', 'wb') as f:
f.write(audio)
```
## Best Practices
1. **Batch requests**: Combine multiple short texts into single requests when possible
2. **Cache audio**: Store generated audio to avoid regenerating the same content
3. **Use streaming**: For long texts, consider using our streaming endpoint
4. **Choose appropriate format**: Use MP3 for web, WAV for professional editing
---
# Voice Cloning
[Canonical source](https://www.speechgen.app/api-docs/voice-clone)
Create custom voice models from audio samples
# Voice Cloning API
Create custom voice models that sound like any voice using our advanced voice cloning technology.
## Endpoint
```http
POST https://api.speechgen.com/v1/voice-clone
Content-Type: multipart/form-data
```
## Request
### Headers
| Header | Value | Required |
| --------------- | --------------------- | -------- |
| `Authorization` | `Bearer YOUR_API_KEY` | Yes |
| `Content-Type` | `multipart/form-data` | Yes |
### Form Data Parameters
### Supported Audio Formats
* MP3 (recommended)
* WAV
* M4A
* FLAC
* OGG
**Audio Requirements:** - Duration: 10 seconds to 5 minutes - Single speaker
only - Clear audio with minimal background noise - File size: Maximum 10MB
### Example Request
```bash
curl -X POST https://api.speechgen.com/v1/voice-clone \
-H "Authorization: Bearer YOUR_API_KEY" \
-F "audio=@voice_sample.mp3" \
-F "name=My Custom Voice" \
-F "description=Professional narrator voice" \
-F "enhance_quality=true"
```
## Response
### Success (201)
```json
{
"model_id": "vm_abc123xyz",
"name": "My Custom Voice",
"description": "Professional narrator voice",
"status": "processing",
"created_at": "2024-01-15T10:30:00Z",
"estimated_completion": "2024-01-15T10:31:00Z",
"samples": [
{
"title": "Default Sample",
"text": "This is a demonstration of the voice clone...",
"audio_url": "https://cdn.speechgen.com/samples/abc123.mp3"
}
]
}
```
### Status Values
| Status | Description |
| ------------ | ---------------------------- |
| `processing` | Voice model is being created |
| `ready` | Voice model is ready to use |
| `failed` | Voice creation failed |
## Check Model Status
```http
GET https://api.speechgen.com/v1/models/{model_id}
```
**Response:**
```json
{
"model_id": "vm_abc123xyz",
"name": "My Custom Voice",
"status": "ready",
"voice_id": "custom-abc123",
"created_at": "2024-01-15T10:30:00Z",
"usage_count": 0
}
```
## Using Your Cloned Voice
Once the model status is `ready`, use the `voice_id` in text-to-speech requests:
```bash
curl -X POST https://api.speechgen.com/v1/text-to-speech \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Hello, this is my cloned voice speaking!",
"voice": "custom-abc123",
"format": "mp3"
}'
```
## Code Examples
### JavaScript
```javascript
async function cloneVoice(audioFile, name, description) {
const formData = new FormData();
formData.append("audio", audioFile);
formData.append("name", name);
formData.append("description", description);
formData.append("enhance_quality", "true");
const response = await fetch("https://api.speechgen.com/v1/voice-clone", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SPEECHGEN_API_KEY}`,
},
body: formData,
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error.message);
}
return response.json();
}
// Poll for completion
async function waitForModel(modelId) {
while (true) {
const response = await fetch(
`https://api.speechgen.com/v1/models/${modelId}`,
{
headers: {
Authorization: `Bearer ${process.env.SPEECHGEN_API_KEY}`,
},
}
);
const model = await response.json();
if (model.status === "ready") return model;
if (model.status === "failed") throw new Error("Voice cloning failed");
await new Promise((r) => setTimeout(r, 5000)); // Wait 5 seconds
}
}
```
### Python
```python
import requests
import time
def clone_voice(audio_path: str, name: str, description: str = "") -> dict:
with open(audio_path, 'rb') as audio_file:
response = requests.post(
'https://api.speechgen.com/v1/voice-clone',
headers={
'Authorization': f'Bearer {os.environ["SPEECHGEN_API_KEY"]}',
},
files={
'audio': audio_file,
},
data={
'name': name,
'description': description,
'enhance_quality': 'true',
}
)
response.raise_for_status()
return response.json()
def wait_for_model(model_id: str) -> dict:
while True:
response = requests.get(
f'https://api.speechgen.com/v1/models/{model_id}',
headers={
'Authorization': f'Bearer {os.environ["SPEECHGEN_API_KEY"]}',
}
)
model = response.json()
if model['status'] == 'ready':
return model
if model['status'] == 'failed':
raise Exception('Voice cloning failed')
time.sleep(5)
```
## Tips for Best Results
**Recording Tips:** 1. Record in a quiet environment with minimal echo 2.
Speak naturally at a consistent pace 3. Keep a consistent distance from the
microphone 4. Avoid background music or noise 5. Record at least 30 seconds
for best quality
## Delete a Voice Model
```http
DELETE https://api.speechgen.com/v1/models/{model_id}
```
**Response:** `204 No Content`
---
# Voices
[Canonical source](https://www.speechgen.app/api-docs/voices)
Explore and list all available voices in our library
# Voices API
Access our library of 100+ premium AI voices across multiple languages and styles.
## List All Voices
```http
GET https://api.speechgen.com/v1/voices
```
### Query Parameters
### Example Request
```bash
curl -X GET "https://api.speechgen.com/v1/voices?language=en-US&gender=female" \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Response
```json
{
"voices": [
{
"id": "en-US-Neural2-A",
"name": "Aria",
"language": "en-US",
"language_name": "English (US)",
"gender": "female",
"styles": ["cheerful", "professional", "calm", "empathetic"],
"preview_url": "https://cdn.speechgen.com/previews/en-US-Neural2-A.mp3",
"is_premium": false
},
{
"id": "en-US-Neural2-B",
"name": "Brandon",
"language": "en-US",
"language_name": "English (US)",
"gender": "male",
"styles": ["professional", "casual", "newscast"],
"preview_url": "https://cdn.speechgen.com/previews/en-US-Neural2-B.mp3",
"is_premium": false
}
],
"total": 150,
"limit": 50,
"offset": 0
}
```
## Get Voice Details
```http
GET https://api.speechgen.com/v1/voices/{voice_id}
```
### Voice Object Properties
### Response
```json
{
"id": "en-US-Neural2-A",
"name": "Aria",
"language": "en-US",
"language_name": "English (US)",
"gender": "female",
"age_group": "adult",
"styles": ["cheerful", "professional", "calm", "empathetic"],
"preview_url": "https://cdn.speechgen.com/previews/en-US-Neural2-A.mp3",
"sample_texts": [
"Hello! I'm Aria, and I'm here to help bring your content to life.",
"Welcome to our platform. Let me guide you through the features."
],
"is_premium": false,
"supported_features": {
"ssml": true,
"speed_control": true,
"pitch_control": true,
"styles": true
}
}
```
## Available Languages
| Language | Code | Voices |
| ------------------- | ------- | ------ |
| English (US) | `en-US` | 24 |
| English (UK) | `en-GB` | 12 |
| Spanish (Spain) | `es-ES` | 10 |
| Spanish (Mexico) | `es-MX` | 8 |
| French | `fr-FR` | 10 |
| German | `de-DE` | 10 |
| Italian | `it-IT` | 8 |
| Portuguese (Brazil) | `pt-BR` | 8 |
| Japanese | `ja-JP` | 6 |
| Korean | `ko-KR` | 6 |
| Chinese (Mandarin) | `zh-CN` | 8 |
| Arabic | `ar-SA` | 4 |
| Hindi | `hi-IN` | 4 |
New voices are added regularly. Check the API for the most up-to-date list.
## Voice Styles
Many voices support multiple speaking styles:
| Style | Description |
| -------------- | -------------------------- |
| `cheerful` | Upbeat and positive |
| `professional` | Formal and authoritative |
| `calm` | Relaxed and soothing |
| `empathetic` | Warm and understanding |
| `newscast` | News anchor style |
| `casual` | Conversational and relaxed |
| `excited` | Energetic and enthusiastic |
### Using Styles
Include the style in your text-to-speech request:
```json
{
"text": "Welcome to our podcast!",
"voice": "en-US-Neural2-A",
"style": "cheerful",
"format": "mp3"
}
```
## Code Examples
### JavaScript
```javascript
async function listVoices(language = null, gender = null) {
const params = new URLSearchParams();
if (language) params.append("language", language);
if (gender) params.append("gender", gender);
const response = await fetch(
`https://api.speechgen.com/v1/voices?${params}`,
{
headers: {
Authorization: `Bearer ${process.env.SPEECHGEN_API_KEY}`,
},
}
);
return response.json();
}
// Get all English female voices
const voices = await listVoices("en-US", "female");
console.log(voices);
```
### Python
```python
import requests
def list_voices(language=None, gender=None):
params = {}
if language:
params['language'] = language
if gender:
params['gender'] = gender
response = requests.get(
'https://api.speechgen.com/v1/voices',
headers={
'Authorization': f'Bearer {os.environ["SPEECHGEN_API_KEY"]}',
},
params=params
)
return response.json()
# Get all Spanish voices
voices = list_voices(language='es-ES')
print(voices)
```
## Custom Voices
In addition to our standard library, you can use your own [cloned voices](/api-docs/voice-clone). Custom voice IDs follow the format `custom-{model_id}`.
```json
{
"text": "This is my custom cloned voice!",
"voice": "custom-abc123xyz",
"format": "mp3"
}
```