import { KovaTTSClient, pcm16ToWavBytes } from "@kova-ai/tts";
import { writeFile } from "node:fs/promises";
const DOCUMENT = [
"Welcome to Kova.",
"This is the second sentence.",
"And here is one more, just to round things out.",
];
const client = new KovaTTSClient({ apiKey: process.env.KOVA_API_KEY! });
const sampleRate = 32000;
const pcmChunks: Uint8Array[] = [];
const ws = await client.connectWebSocket();
await ws.startContext({
contextId: "doc",
voiceId: "cal",
modelId: "default",
responseFormat: { encoding: "pcm", sample_rate: sampleRate },
});
for (const line of DOCUMENT) {
await ws.sendText("doc", line + " ");
}
await ws.flush("doc", "end");
for await (const frame of ws) {
if (frame.type === "audio") {
pcmChunks.push(frame.audio);
} else if (frame.type === "flush_completed" && frame.flush_id === "end") {
break;
}
}
await ws.closeContext("doc");
ws.close();
const total = pcmChunks.reduce((n, c) => n + c.byteLength, 0);
const merged = new Uint8Array(total);
let offset = 0;
for (const c of pcmChunks) { merged.set(c, offset); offset += c.byteLength; }
// The SDK does not currently expose a WAV-writing helper on the client.
// Use the exported `pcm16ToWavBytes` primitive + node:fs to write the file.
const wavBytes = pcm16ToWavBytes(merged, { sampleRate });
await writeFile("doc.wav", wavBytes);
console.log(`wrote doc.wav (${total} pcm bytes)`);