Code Examples
Ready-to-use code examples in multiple programming languages.
Python
Basic Generation
python
import requests
def generate_tts(text, voice="Peter", format="wav"):
response = requests.post(
"https://yourvoic.com/api/v1/tts/generate",
headers={"X-API-Key": "your_api_key"},
json={"text": text, "voice": voice, "format": format}
)
return response.content
# Generate and save (default WAV format)
audio = generate_tts("Hello, welcome to YourVoic!")
with open("output.wav", "wb") as f:
f.write(audio)
# Or use MP3 for smaller files
audio_mp3 = generate_tts("Hello!", format="mp3")
with open("output.mp3", "wb") as f:
f.write(audio_mp3)
With Error Handling
python
import requests
import time
class YourVoicClient:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://yourvoic.com/api/v1"
def generate(self, text, voice="Peter", model="aura-prime", retries=3):
for attempt in range(retries):
try:
response = requests.post(
f"{self.base_url}/tts/generate",
headers={"X-API-Key": self.api_key},
json={"text": text, "voice": voice, "model": model},
timeout=30
)
if response.status_code == 200:
return response.content
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", 60))
time.sleep(retry_after)
continue
response.raise_for_status()
except requests.exceptions.RequestException as e:
if attempt == retries - 1:
raise
time.sleep(2 ** attempt)
raise Exception("Max retries exceeded")
# Usage
client = YourVoicClient("your_api_key")
audio = client.generate("Hello world!", voice="Sarah")
JavaScript / Node.js
Node.js with Fetch
javascript
const fs = require('fs');
async function generateTTS(text, voice = 'Peter') {
const response = await fetch('https://yourvoic.com/api/v1/tts/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'your_api_key'
},
body: JSON.stringify({ text, voice })
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error?.message || 'API request failed');
}
return Buffer.from(await response.arrayBuffer());
}
// Usage
const audio = await generateTTS('Hello from Node.js!');
fs.writeFileSync('output.mp3', audio);
Browser (Client-Side)
javascript
async function playTTS(text) {
const response = await fetch('https://yourvoic.com/api/v1/tts/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'your_api_key' // Use server-side proxy in production!
},
body: JSON.stringify({ text, voice: 'Peter' })
});
const audioBlob = await response.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.play();
}
// Usage
playTTS('Hello from the browser!');
cURL
bash
# Basic request
curl -X POST "https://yourvoic.com/api/v1/tts/generate" \
-H "Content-Type: application/json" \
-H "X-API-Key: your_api_key" \
-d '{"text": "Hello world!", "voice": "Peter"}' \
--output output.mp3
# With all parameters
curl -X POST "https://yourvoic.com/api/v1/tts/generate" \
-H "Content-Type: application/json" \
-H "X-API-Key: your_api_key" \
-d '{
"text": "Welcome to YourVoic!",
"voice": "Sarah",
"model": "aura-prime",
"speed": 1.0,
"pitch": 0.0,
"audio_format": "mp3"
}' \
--output welcome.mp3
# List voices
curl "https://yourvoic.com/api/v1/voices?language=en-US" \
-H "X-API-Key: your_api_key"
# Check usage
curl "https://yourvoic.com/api/v1/usage" \
-H "X-API-Key: your_api_key"
🔴 Real-Time Streaming
Stream audio in real-time with low-latency delivery. Supports multiple models with different audio formats: Aura (PCM), Rapid Max (OGG Opus), Rapid Flash (WAV).
Streaming with cURL
bash
# Aura models stream PCM (requires conversion)
curl -N -X POST "https://yourvoic.com/api/v1/tts/stream" \
-H "Content-Type: application/json" \
-H "X-API-Key: your_api_key" \
-d '{"text": "Hello, this is streaming audio!", "voice": "Peter", "model": "aura-lite"}' \
--output streaming.pcm
# Convert raw PCM to WAV for playback
ffmpeg -f s16le -ar 24000 -ac 1 -i streaming.pcm streaming.wav
# Rapid Max streams OGG Opus (plays directly)
curl -N -X POST "https://yourvoic.com/api/v1/tts/stream" \
-H "Content-Type: application/json" \
-H "X-API-Key: your_api_key" \
-d '{"text": "HD quality streaming!", "voice": "Peter", "model": "rapid-max"}' \
--output streaming.ogg
# Rapid Flash streams WAV (plays directly)
curl -N -X POST "https://yourvoic.com/api/v1/tts/stream" \
-H "Content-Type: application/json" \
-H "X-API-Key: your_api_key" \
-d '{"text": "Fast voice streaming!", "voice": "Jacob", "model": "rapid-flash", "language": "en-US"}' \
--output streaming.wav
# Play directly with sox (Aura PCM)
curl -N -X POST "https://yourvoic.com/api/v1/tts/stream" \
-H "Content-Type: application/json" \
-H "X-API-Key: your_api_key" \
-d '{"text": "Playing in real-time!", "voice": "Peter", "model": "aura-lite"}' | \
play -t raw -r 24000 -e signed -b 16 -c 1 -
Python Streaming
python
import requests
class StreamingTTS:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://yourvoic.com/api/v1"
def stream(self, text, voice="Peter", model="aura-lite", language="en-US"):
"""
Stream audio chunks in real-time.
Models and their output formats:
- aura-lite/prime/max: PCM (raw audio, needs conversion)
- rapid-max: OGG Opus (playable directly)
- rapid-flash: WAV (playable directly)
"""
response = requests.post(
f"{self.base_url}/tts/stream",
headers={
"X-API-Key": self.api_key,
"Content-Type": "application/json"
},
json={"text": text, "voice": voice, "model": model, "language": language},
stream=True
)
for chunk in response.iter_content(chunk_size=1024):
yield chunk
def stream_to_file(self, text, output_path, voice="Peter", model="aura-lite", language="en-US"):
"""Stream and save to file. Extension depends on model."""
with open(output_path, 'wb') as f:
for chunk in self.stream(text, voice, model, language):
f.write(chunk)
# Usage
client = StreamingTTS("your_api_key")
# Aura models (PCM - requires conversion to play)
client.stream_to_file("Hello world!", "output.pcm", model="aura-lite")
# Convert: ffmpeg -f s16le -ar 24000 -ac 1 -i output.pcm output.wav
# Rapid Max (OGG Opus - plays directly)
client.stream_to_file("HD quality audio!", "output.ogg", model="rapid-max")
# Rapid Flash (WAV - plays directly)
client.stream_to_file("Fast voice!", "output.wav", voice="Jacob", model="rapid-flash")
JavaScript Browser Streaming
javascript
class StreamingTTS {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = '/api/v1';
}
/**
* Stream audio to speakers
* @param {string} text - Text to convert
* @param {string} voice - Voice name
* @param {string} model - Model: aura-lite, aura-prime, aura-max, rapid-max, rapid-flash
* @param {string} language - Language code (required for rapid-flash)
*/
async stream(text, voice = 'Peter', model = 'aura-lite', language = 'en-US') {
const response = await fetch(`${this.baseUrl}/tts/stream`, {
method: 'POST',
headers: {
'X-API-Key': this.apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({ text, voice, model, language })
});
const audioContext = new AudioContext({ sampleRate: 24000 });
const reader = response.body.getReader();
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
}
// Combine chunks
const totalLength = chunks.reduce((acc, c) => acc + c.length, 0);
const audioData = new Uint8Array(totalLength);
let offset = 0;
chunks.forEach(chunk => { audioData.set(chunk, offset); offset += chunk.length; });
// Handle different formats based on model
if (model === 'rapid-max' || model === 'rapid-flash') {
// OGG Opus or WAV - use decodeAudioData
const arrayBuffer = audioData.buffer.slice(audioData.byteOffset, audioData.byteOffset + audioData.byteLength);
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start();
return source;
} else {
// Aura models - PCM format
const samples = new Int16Array(audioData.buffer);
const float32 = new Float32Array(samples.length);
for (let i = 0; i < samples.length; i++) float32[i] = samples[i] / 32768;
const buffer = audioContext.createBuffer(1, float32.length, 24000);
buffer.copyToChannel(float32, 0);
const source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(audioContext.destination);
source.start();
return source;
}
}
}
// Usage examples
const tts = new StreamingTTS('your_api_key');
// Aura model (PCM)
await tts.stream('Hello world!', 'Peter', 'aura-lite');
// Rapid Max (OGG Opus)
await tts.stream('HD quality!', 'Peter', 'rapid-max');
// Rapid Flash (WAV)
await tts.stream('Fast voice!', 'Jacob', 'rapid-flash', 'en-US');
Node.js Streaming
javascript
const fs = require('fs');
/**
* Stream TTS to file
* @param {string} text - Text to convert
* @param {string} outputPath - Output file path
* @param {object} options - { voice, model, language }
*/
async function streamTTS(text, outputPath, options = {}) {
const { voice = 'Peter', model = 'aura-lite', language = 'en-US' } = options;
const response = await fetch('https://yourvoic.com/api/v1/tts/stream', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'your_api_key'
},
body: JSON.stringify({ text, voice, model, language })
});
const writer = fs.createWriteStream(outputPath);
const reader = response.body.getReader();
const startTime = Date.now();
let totalBytes = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (totalBytes === 0) console.log(`TTFB: ${Date.now() - startTime}ms`);
writer.write(Buffer.from(value));
totalBytes += value.length;
}
writer.end();
console.log(`${totalBytes} bytes in ${Date.now() - startTime}ms`);
}
// Aura (PCM - convert with ffmpeg)
await streamTTS('Hello!', 'output.pcm', { model: 'aura-lite' });
// Rapid Max (OGG Opus - plays directly)
await streamTTS('HD audio!', 'output.ogg', { model: 'rapid-max' });
// Rapid Flash (WAV - plays directly)
await streamTTS('Hello!', 'output.wav', { voice: 'Jacob', model: 'rapid-flash' });
💡 Streaming Models & Formats:
aura-lite,aura-prime,aura-max→ PCM (16-bit, 24kHz, mono)rapid-max→ OGG Opus (compressed, playable)rapid-flash→ WAV (playable directly)
PHP
php
<?php
function generateTTS($text, $voice = 'Peter') {
$ch = curl_init('https://yourvoic.com/api/v1/tts/generate');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'X-API-Key: your_api_key'
],
CURLOPT_POSTFIELDS => json_encode([
'text' => $text,
'voice' => $voice
])
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception('API request failed: ' . $response);
}
return $response;
}
// Usage
$audio = generateTTS('Hello from PHP!');
file_put_contents('output.mp3', $audio);
Java
java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
public class YourVoicClient {
private final HttpClient client = HttpClient.newHttpClient();
private final String apiKey;
public YourVoicClient(String apiKey) {
this.apiKey = apiKey;
}
public byte[] generate(String text, String voice) throws Exception {
String json = """
{
"text": "%s",
"voice": "%s",
"model": "aura-prime"
}
""".formatted(text, voice);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://yourvoic.com/api/v1/tts/generate"))
.header("X-API-Key", apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<byte[]> response = client.send(request,
HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() != 200) {
throw new RuntimeException("API request failed: " + response.statusCode());
}
return response.body();
}
public static void main(String[] args) throws Exception {
YourVoicClient client = new YourVoicClient("your_api_key");
byte[] audio = client.generate("Hello from Java!", "Peter");
Files.write(Path.of("output.mp3"), audio);
System.out.println("✅ Audio saved to output.mp3");
}
}
Go
go
package main
import (
"bytes"
"encoding/json"
"io"
"net/http"
"os"
)
type TTSRequest struct {
Text string `json:"text"`
Voice string `json:"voice"`
}
func generateTTS(text, voice string) ([]byte, error) {
payload, _ := json.Marshal(TTSRequest{Text: text, Voice: voice})
req, _ := http.NewRequest("POST",
"https://yourvoic.com/api/v1/tts/generate",
bytes.NewBuffer(payload))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Key", "your_api_key")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
func main() {
audio, _ := generateTTS("Hello from Go!", "Peter")
os.WriteFile("output.mp3", audio, 0644)
}
Ruby
ruby
require 'net/http'
require 'json'
def generate_tts(text, voice = 'Peter')
uri = URI('https://yourvoic.com/api/v1/tts/generate')
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
request['X-API-Key'] = 'your_api_key'
request.body = { text: text, voice: voice }.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
response.body
end
# Usage
audio = generate_tts('Hello from Ruby!')
File.binwrite('output.mp3', audio)
C# / .NET
csharp
using System.Net.Http;
using System.Text;
using System.Text.Json;
public class YourVoicClient
{
private readonly HttpClient _client;
public YourVoicClient(string apiKey)
{
_client = new HttpClient();
_client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
}
public async Task<byte[]> GenerateAsync(string text, string voice = "Peter")
{
var payload = JsonSerializer.Serialize(new { text, voice });
var content = new StringContent(payload, Encoding.UTF8, "application/json");
var response = await _client.PostAsync(
"https://yourvoic.com/api/v1/tts/generate",
content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsByteArrayAsync();
}
}
// Usage
var client = new YourVoicClient("your_api_key");
var audio = await client.GenerateAsync("Hello from C#!");
await File.WriteAllBytesAsync("output.mp3", audio);