code icon Code

Text to Speech

Convert text to speech using ElevenLabs API

Source Code

import fs from "fs";
import path from "path";

const apiKey = "15fd8afd4509c340bf5af364d6fd32a2a8728b0eaa658a1c1323da68477ab804";

const [text, voiceId, modelId = "eleven_multilingual_v2", outputFormat = "mp3_44100_128"] =
  process.argv.slice(2);

if (!text) {
  console.error("Error: text is required");
  process.exit(1);
}

if (!voiceId) {
  console.error("Error: voiceId is required");
  process.exit(1);
}

async function main() {
  const url = `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}?output_format=${outputFormat}`;

  console.log(`Generating speech for: "${text.substring(0, 50)}${text.length > 50 ? "..." : ""}"`);
  console.log(`Voice ID: ${voiceId}`);
  console.log(`Model: ${modelId}`);

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "xi-api-key": apiKey,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      text: text,
      model_id: modelId,
    }),
  });

  if (!response.ok) {
    const errorText = await response.text();
    console.error(`API error (${response.status}): ${errorText}`);
    process.exit(1);
  }

  const audioBuffer = await response.arrayBuffer();

  const outputDir = "audio/generated";
  fs.mkdirSync(outputDir, { recursive: true });

  const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
  const ext = outputFormat.startsWith("mp3") ? "mp3" : outputFormat.startsWith("pcm") ? "wav" : "mp3";
  const outputPath = path.join(outputDir, `${timestamp}.${ext}`);

  fs.writeFileSync(outputPath, Buffer.from(audioBuffer));

  const charCount = response.headers.get("x-character-count");

  console.log(`✓ Audio saved to: ${outputPath}`);
  console.log(
    JSON.stringify(
      {
        success: true,
        path: outputPath,
        voiceId: voiceId,
        model: modelId,
        format: outputFormat,
        characterCount: charCount || text.length,
        textLength: text.length,
      },
      null,
      2
    )
  );
}

main().catch((err) => {
  console.error("Error:", err.message);
  process.exit(1);
});