Complete, copy-paste ready examples for TTS using HTTP and Server-Sent Events (SSE).
Quick Start
Basic HTTP Request
Convert text to speech and receive complete audio file:
curl https://api.slng.ai/v1/tts/deepgram/aura:2 \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Hello! This is a text-to-speech example.",
"encoding": "linear16",
"sample_rate": 24000
}' \
--output audio.raw
Response: Binary PCM audio data
HTTP Examples by Language
cURL
Basic Request
curl https://api.slng.ai/v1/tts/deepgram/aura:2 \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Convert this text to speech",
"encoding": "linear16",
"sample_rate": 24000
}' \
--output output.raw
With Voice Selection (Deepgram Aura)
curl https://api.slng.ai/v1/tts/deepgram/aura:2 \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Hello from a specific voice!",
"voice": "asteria-en",
"encoding": "linear16",
"sample_rate": 24000
}' \
--output output.raw
JavaScript/TypeScript
Basic Request
const response = await fetch("https://api.slng.ai/v1/tts/deepgram/aura:2", {
method: "POST",
headers: {
Authorization: "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
},
body: JSON.stringify({
text: "Hello from JavaScript!",
encoding: "linear16",
sample_rate: 24000,
}),
});
const audioData = await response.arrayBuffer();
// Play or save audioData
Complete Example with Audio Playback
async function textToSpeech(text) {
try {
const response = await fetch("https://api.slng.ai/v1/tts/deepgram/aura:2", {
method: "POST",
headers: {
Authorization: "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
},
body: JSON.stringify({
text: text,
encoding: "linear16",
sample_rate: 24000,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const audioData = await response.arrayBuffer();
// Play audio using Web Audio API
const audioContext = new AudioContext();
const audioBuffer = await audioContext.decodeAudioData(audioData);
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start(0);
} catch (error) {
console.error("TTS Error:", error);
}
}
// Usage
textToSpeech("Hello! This is a complete example.");
With ElevenLabs
const response = await fetch(
"https://api.slng.ai/v1/tts/elevenlabs/eleven-flash:2.5",
{
method: "POST",
headers: {
Authorization: "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
},
body: JSON.stringify({
text: "ElevenLabs provides premium voice quality with ultra-low latency.",
encoding: "linear16",
sample_rate: 24000,
}),
},
);
const audioData = await response.arrayBuffer();
Python
Basic Request
import requests
url = "https://api.slng.ai/v1/tts/deepgram/aura:2"
headers = {
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
}
data = {
"text": "Hello from Python!",
"encoding": "linear16",
"sample_rate": 24000
}
response = requests.post(url, headers=headers, json=data)
audio_data = response.content
# Save to file
with open("output.raw", "wb") as f:
f.write(audio_data)
Complete Example with Error Handling
import requests
from typing import Optional
def text_to_speech(
text: str,
provider: str = "deepgram",
model: str = "aura",
variant: str = "2",
voice: Optional[str] = None,
api_key: str = "YOUR_API_KEY"
) -> bytes:
"""
Convert text to speech using SLNG API.
Args:
text: Text to convert to speech
provider: TTS provider (deepgram, elevenlabs, slng)
model: Model name (aura, eleven, orpheus)
variant: Model variant (2, flash-v2.5, en)
voice: Optional voice ID
api_key: SLNG API key
Returns:
Raw audio bytes (PCM format)
"""
url = f"https://api.slng.ai/v1/tts/{provider}/{model}:{variant}"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"text": text,
"encoding": "linear16",
"sample_rate": 24000
}
if voice:
payload["voice"] = voice
try:
response = requests.post(url, headers=headers, json=payload, timeout=30)
response.raise_for_status()
return response.content
except requests.exceptions.HTTPError as e:
print(f"HTTP Error: {e}")
print(f"Response: {response.text}")
raise
except requests.exceptions.RequestException as e:
print(f"Request Error: {e}")
raise
# Usage
audio = text_to_speech("Hello! This is a complete Python example.")
with open("output.raw", "wb") as f:
f.write(audio)
Server-Sent Events (SSE) - Progressive Streaming
SSE allows you to receive audio chunks progressively as they're generated, enabling lower latency playback.
JavaScript SSE Example
async function streamTTS(text) {
const response = await fetch("https://api.slng.ai/v1/tts/deepgram/aura:2", {
method: "POST",
headers: {
Authorization: "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
Accept: "text/event-stream", // Request SSE streaming
},
body: JSON.stringify({
text: text,
encoding: "linear16",
sample_rate: 24000,
}),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split("\n");
for (const line of lines) {
if (line.startsWith("data: ")) {
const data = JSON.parse(line.slice(6));
if (data.type === "audio") {
// Decode base64 audio chunk
const audioChunk = atob(data.data);
const audioArray = new Uint8Array(audioChunk.length);
for (let i = 0; i < audioChunk.length; i++) {
audioArray[i] = audioChunk.charCodeAt(i);
}
// Play audio chunk immediately
playAudioChunk(audioArray);
} else if (data.type === "done") {
console.log("Streaming complete");
break;
}
}
}
}
}
// Usage
streamTTS("This text will be streamed progressively as audio chunks.");
Python SSE Example
import requests
import json
import base64
def stream_tts(text: str, api_key: str = "YOUR_API_KEY"):
"""
Stream TTS using Server-Sent Events for progressive audio delivery.
"""
url = "https://api.slng.ai/v1/tts/deepgram/aura:2"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"Accept": "text/event-stream"
}
data = {
"text": text,
"encoding": "linear16",
"sample_rate": 24000
}
with requests.post(url, headers=headers, json=data, stream=True) as response:
response.raise_for_status()
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
event_data = json.loads(line[6:])
if event_data['type'] == 'audio':
# Decode base64 audio chunk
audio_chunk = base64.b64decode(event_data['data'])
# Process or play audio_chunk immediately
yield audio_chunk
elif event_data['type'] == 'done':
print("Streaming complete")
break
# Usage
audio_chunks = []
for chunk in stream_tts("Progressive streaming with Python!"):
audio_chunks.append(chunk)
# Play chunk immediately for low-latency playback
# Or save all chunks
with open("output.raw", "wb") as f:
f.writelines(audio_chunks)
Common Parameters
All Models
| Parameter | Type | Required | Description |
|---|
text | string | Yes | Text to convert to speech |
encoding | string | Yes | Audio encoding (linear16, mulaw, alaw) |
sample_rate | number | Yes | Sample rate in Hz (8000, 16000, 24000, 48000) |
voice | string | No | Voice ID (provider-specific) |
Deepgram Aura Voices
Common voices include:
asteria-en - Female, neutral
luna-en - Female, warm
stella-en - Female, young
athena-en - Female, confident
hera-en - Female, authoritative
orion-en - Male, deep
arcas-en - Male, friendly
perseus-en - Male, professional
angus-en - Male, warm
helios-en - Male, energetic
Spanish voices:
asteria-es - Female Spanish
luna-es - Female Spanish
See Deepgram Aura API reference for full voice list
ElevenLabs Eleven
Premium voices with voice cloning support. Refer to ElevenLabs documentation for voice IDs.
SLNG Orpheus
8 emotion-capable voices:
male_1 through male_4
female_1 through female_4
Supports emotion tags: <happy>, <sad>, <angry>, <excited>
Error Handling
HTTP Status Codes
| Code | Meaning | Solution |
|---|
200 | Success | Audio data returned |
400 | Bad Request | Check request parameters |
401 | Unauthorized | Verify API key |
429 | Rate Limited | Implement backoff |
500 | Server Error | Retry with exponential backoff |
Example with Retry Logic
async function ttsWithRetry(text, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(
"https://api.slng.ai/v1/tts/deepgram/aura:2",
{
method: "POST",
headers: {
Authorization: "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
},
body: JSON.stringify({
text: text,
encoding: "linear16",
sample_rate: 24000,
}),
},
);
if (response.status === 429) {
// Rate limited - wait and retry
const delay = Math.pow(2, i) * 1000; // Exponential backoff
console.log(`Rate limited. Retrying in ${delay}ms...`);
await new Promise((resolve) => setTimeout(resolve, delay));
continue;
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
return await response.arrayBuffer();
} catch (error) {
if (i === maxRetries - 1) throw error;
console.log(`Attempt ${i + 1} failed. Retrying...`);
}
}
}
Last modified on