Generate Speech
Guide to generating speech from text with KugelAudio: basic and async generation, common parameters, browser playback and pre-connecting for lower latency.
On this page
Generate complete audio from text. This is the simplest way to get started: provide text and receive audio back.
Basic Generation
from kugelaudio import KugelAudio
client = KugelAudio(api_key="your_api_key")
audio = client.tts.generate(
text="Hello, this is a test of the KugelAudio text-to-speech system.",
model_id="kugel-3.5",
voice_id=1071,
)
# Save to file
audio.save("output.wav")
# Or get WAV bytes
wav_bytes = audio.to_wav_bytes()import { KugelAudio } from 'kugelaudio';
const client = new KugelAudio({ apiKey: 'your_api_key' });
const audio = await client.tts.generate({
text: 'Hello, this is a test of the KugelAudio text-to-speech system.',
modelId: 'kugel-3.5',
voiceId: 1071,
});
// audio.audio is an ArrayBuffer with PCM16 data
console.log(`Duration: ${audio.durationMs}ms`);import com.kugelaudio.sdk.KugelAudio;
import com.kugelaudio.sdk.KugelAudioOptions;
import com.kugelaudio.sdk.GenerateRequest;
import com.kugelaudio.sdk.AudioResponse;
KugelAudio client = new KugelAudio(
KugelAudioOptions.builder("your_api_key").build()
);
AudioResponse audio = client.tts().generate(
GenerateRequest.builder("Hello, this is a test of the KugelAudio text-to-speech system.")
.modelId("kugel-3.5")
.voiceId(1071)
.language("en")
.build()
);
// Save to WAV file
audio.saveWav(java.nio.file.Path.of("output.wav"));
// Or get raw PCM bytes
byte[] pcmData = audio.getAudio();curl -X POST https://api.kugelaudio.com/v1/tts/generate \
-H "Authorization: Bearer $KUGELAUDIO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Hello, this is a test of the KugelAudio text-to-speech system.",
"model_id": "kugel-3.5",
"voice_id": 1071
}' \
--output output.pcm
# The response is raw PCM16 audio (signed 16-bit LE, mono, 24kHz)
# Convert to WAV for playback:
ffmpeg -f s16le -ar 24000 -ac 1 -i output.pcm output.wavGeneration Parameters
The parameters you'll touch most often (Python/REST snake_case; JavaScript uses camelCase):
text(required) andmodel_id:kugel-3.5(the default) orkugel-3(Models)voice_id: the voice to speak with (Using voices)cfg_scale: expressiveness (see the guide below)temperature: sampling randomness (0to1); omit it to use the model defaultnormalize+language: text normalization. Always set the language when you know it; otherwise each sentence's language is recognized from its words, falling back to the voice's primary languagespeed: playback rate (see Speed control below)word_timestamps: word-level timestamps. SDK and WebSocket only;POST /v1/tts/generaterejects it with400
The Generate Speech API reference
is the canonical parameter table: every field with type, default, range, and
error behavior, including output_format, project_id, and dictionary_ids.
CFG Scale Guide
The cfg_scale parameter controls how closely the model follows the voice characteristics. Accepted range: 1.2–2.5 (inclusive). Values outside this range are clamped into it.
| Range | Style | Best For |
|---|---|---|
| 1.2-1.5 | Relaxed, natural | Conversational AI, long-form narration |
| 2.0 | Balanced (default) | General purpose |
| 2.5 | Expressive | Storytelling, emphasis-heavy content |
Speed Control
speed changes the playback rate of the whole request with pitch-preserving
time-stretching. The range is 0.8 to 1.2 (default 1.0); values outside
it are rejected (400 on REST). To change the rate for part of a request,
wrap that text in <prosody rate="...">. Examples and rules:
Speed and
per-span speed.
For pauses, codes, and pronunciation fixes, see the
Prompting guide: <break> tags,
<spell> tags, and the
unsupported-tags table.
Example with Common Options
audio = client.tts.generate(
text="Hello, this is a test of the KugelAudio text-to-speech system.",
model_id="kugel-3.5",
voice_id=1071,
cfg_scale=2.0,
max_new_tokens=2048,
sample_rate=24000,
normalize=True,
language="en",
word_timestamps=False,
speed=1.0,
)
# Inspect the response
print(f"Duration: {audio.duration_seconds:.2f}s")
print(f"Samples: {audio.samples}")
print(f"Sample rate: {audio.sample_rate} Hz")
print(f"Generation time: {audio.generation_ms:.0f}ms")
print(f"RTF: {audio.rtf:.2f}")
# Save to WAV file
audio.save("output.wav")
# Get raw PCM bytes
pcm_data = audio.audio
# Get WAV bytes (with header)
wav_bytes = audio.to_wav_bytes()const audio = await client.tts.generate({
text: 'Hello, this is a test of the KugelAudio text-to-speech system.',
modelId: 'kugel-3.5',
voiceId: 1071,
cfgScale: 2.0,
maxNewTokens: 2048,
sampleRate: 24000,
normalize: true,
language: 'en',
wordTimestamps: false,
speed: 1.0,
});
// Inspect the response
console.log(`Duration: ${audio.durationMs}ms`);
console.log(`Samples: ${audio.samples}`);
console.log(`Sample rate: ${audio.sampleRate} Hz`);
console.log(`Generation time: ${audio.generationMs}ms`);
console.log(`RTF: ${audio.rtf}`);
// audio.audio is an ArrayBuffer with PCM16 dataAudioResponse audio = client.tts().generate(
GenerateRequest.builder("Hello, this is a test of the KugelAudio text-to-speech system.")
.modelId("kugel-3.5")
.voiceId(1071)
.cfgScale(2.0)
.maxNewTokens(2048)
.sampleRate(24000)
.normalize(true)
.language("en")
.wordTimestamps(false)
.speed(1.0)
.build()
);
// Inspect the response
System.out.printf("Duration: %.2fs%n", audio.getDurationMs() / 1000.0);
System.out.printf("Samples: %d%n", audio.getTotalSamples());
System.out.printf("Sample rate: %d Hz%n", audio.getSampleRate());
System.out.printf("Generation time: %.0fms%n", audio.getGenerationMs());
System.out.printf("RTF: %.2f%n", audio.getRtf());
// Save to WAV file
audio.saveWav(java.nio.file.Path.of("output.wav"));curl -X POST https://api.kugelaudio.com/v1/tts/generate \
-H "Authorization: Bearer $KUGELAUDIO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Hello, this is a test of the KugelAudio text-to-speech system.",
"model_id": "kugel-3.5",
"voice_id": 1071,
"cfg_scale": 2.0,
"max_new_tokens": 2048,
"sample_rate": 24000,
"normalize": true,
"language": "en",
"speed": 1.0
}' \
--output output.pcmAsync Generation
import asyncio
async def main():
audio = await client.tts.generate_async(
text="Async generation example.",
model_id="kugel-3.5",
voice_id=1071,
)
audio.save("async_output.wav")
asyncio.run(main())// JavaScript SDK is async by default
const audio = await client.tts.generate({
text: 'Async generation example.',
modelId: 'kugel-3.5',
voiceId: 1071,
});// Java SDK is synchronous by default.
// Use a thread pool for concurrent requests:
import java.util.concurrent.*;
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<AudioResponse> future = executor.submit(() ->
client.tts().generate(
GenerateRequest.builder("Async generation example.")
.modelId("kugel-3.5")
.voiceId(1071)
.language("en")
.build()
)
);
AudioResponse audio = future.get();
audio.saveWav(java.nio.file.Path.of("async_output.wav"));
} finally {
executor.shutdown();
}# cURL requests are synchronous by default; the response
# streams back as the audio is generated.
curl -X POST https://api.kugelaudio.com/v1/tts/generate \
-H "Authorization: Bearer $KUGELAUDIO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Async generation example.",
"model_id": "kugel-3.5",
"voice_id": 1071
}' \
--output async_output.pcmPlaying Audio in the Browser
The JavaScript SDK provides utility functions for audio playback:
import { KugelAudio, createWavBlob } from 'kugelaudio';
const client = new KugelAudio({ apiKey: 'your_api_key' });
const audio = await client.tts.generate({
text: 'Hello, world!',
modelId: 'kugel-3.5',
voiceId: 1071,
});
// Create WAV blob for playback
const wavBlob = createWavBlob(audio.audio, audio.sampleRate);
const url = URL.createObjectURL(wavBlob);
// Play with Audio element
const audioElement = new Audio(url);
audioElement.play();
// Or with Web Audio API
const audioContext = new AudioContext();
const arrayBuffer = await wavBlob.arrayBuffer();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start();Pre-connecting for Low Latency
For latency-sensitive applications, open the WebSocket connection at application startup so the handshake is not part of your first request. The per-SDK calls are in Latency: Pre-connect at startup.
Word Timestamps
Per-word time alignments (for subtitles, karaoke, lip-sync, and barge-in) are
available from the SDKs and the WebSocket endpoints, not from
POST /v1/tts/generate. See Word timestamps.