Text to speech: save or stream
Turn text into HUMAIN Voice speech and save it as a WAV file or play it as the audio arrives.
You turn text into speech, either saved to speech.wav or played while it's generated. Install the
SDK and set API_URL and API_KEY as in the Quickstart. Socket.IO examples
also read the optional API_PATH (Connection settings).
Save when you need the whole clip, stream when playback should start early
(Speech output).
Pick a voice
Send a voice id from the voice list as voice_id; IDs differ per environment, so look them up
(Voice list). The examples pick one from the list at run time.
Save speech to a WAV file
The example takes the text and the output path as arguments (defaults: Hello from HUMAIN Voice
and speech.wav), prints the chosen voice, and writes the WAV file.
import { writeFile } from 'node:fs/promises';
import {
TTSClient,
TtsModel,
getSampleRate,
} from '@humain-voice/sdk';
function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
const value = process.env[name];
if (!value) throw new Error(`${name} is required`);
return value;
}
function socketPath(): { api_path?: string } {
const value = process.env.API_PATH;
return value ? { api_path: value } : {};
}
function pcm16ToWav(pcm: Uint8Array, sampleRate: number): Buffer {
const header = Buffer.alloc(44);
header.write('RIFF', 0);
header.writeUInt32LE(36 + pcm.byteLength, 4);
header.write('WAVE', 8);
header.write('fmt ', 12);
header.writeUInt32LE(16, 16);
header.writeUInt16LE(1, 20); // Linear PCM.
header.writeUInt16LE(1, 22); // Mono.
header.writeUInt32LE(sampleRate, 24);
header.writeUInt32LE(sampleRate * 2, 28);
header.writeUInt16LE(2, 32);
header.writeUInt16LE(16, 34);
header.write('data', 36);
header.writeUInt32LE(pcm.byteLength, 40);
return Buffer.concat([
header,
Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength),
]);
}
async function main(): Promise<void> {
const text = process.argv[2] ?? 'Hello from HUMAIN Voice';
const outputPath = process.argv[3] ?? 'speech.wav';
const client = new TTSClient({
api_url: requiredEnv('API_URL'),
api_key: requiredEnv('API_KEY'),
...socketPath(),
});
try {
const voices = await client.listVoices({ timeoutSeconds: 5 });
const voice = voices.find((candidate) => candidate.profile) ?? voices[0];
if (!voice) throw new Error('No TTS voices are available');
if (voice.profile) {
console.info(
'status:',
'voice',
voice.label,
voice.profile.speaker.dialect,
voice.profile.languages,
);
}
const model = TtsModel.Nebula;
const pcm = await client.synthesize(text, {
voice_id: voice.id,
model,
// Inactivity timeout per audio chunk, not a total deadline.
timeoutSeconds: 30,
onError: (error) => console.error('error:', error.code, error.message),
});
await writeFile(outputPath, pcm16ToWav(pcm, getSampleRate(model)));
} finally {
await client.close();
}
}
void main().catch((error: unknown) => {
console.error(error);
process.exitCode = 1;
});
Expected output (illustrative):
status: voice mul_nourah ars [ 'ar', 'en' ]The SDK returns raw PCM16 audio, 24 kHz, mono; the example adds the 44-byte WAV header so players can open it.
Play speech as it streams
The example writes raw PCM to stdout as each chunk arrives and logs to stderr, so you can pipe the audio straight into a player:
import { TTSClient, TtsModel, getSampleRate } from '@humain-voice/sdk';
function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
const value = process.env[name];
if (!value) throw new Error(`${name} is required`);
return value;
}
function socketPath(): { api_path?: string } {
const value = process.env.API_PATH;
return value ? { api_path: value } : {};
}
async function main(): Promise<void> {
const text = process.argv[2] ?? 'Hello from HUMAIN Voice';
const model = TtsModel.Nebula;
const client = new TTSClient({
api_url: requiredEnv('API_URL'),
api_key: requiredEnv('API_KEY'),
...socketPath(),
});
try {
const [voice] = await client.listVoices({ timeoutSeconds: 5 });
if (!voice) throw new Error('No TTS voices are available');
// Audio goes to stdout, so logs go to stderr.
console.error('status: sample rate', getSampleRate(model));
for await (const chunk of client.synthesizeStream(text, {
voice_id: voice.id,
model,
timeoutSeconds: 30,
onError: (error) => console.error('error:', error.code, error.message),
})) {
process.stdout.write(chunk.audio);
}
} finally {
await client.close();
}
}
void main().catch((error: unknown) => {
console.error(error);
process.exitCode = 1;
});
node tts-stream.ts "Hello from HUMAIN Voice" | ffplay -f s16le -ar 24000 -ch_layout mono -Expected stderr output (illustrative):
status: sample rate 24000If an error: line arrives, the clip is incomplete; discard any audio you saved.
Errors and timeouts
Error codes and fixes are in Text-to-speech codes.
The examples wait up to 30 seconds for each next chunk; Python has no default, so always pass
timeout_seconds (JavaScript,
Python).