Text to Speech
Convert text to speech using ElevenLabs API
Source Code
import fs from "fs";
import path from "path";
const apiKey = "PLACEHOLDER_TOKEN";
const [textFilePath, voiceId, modelId = "eleven_multilingual_v2", outputFormat = "mp3_44100_128", outputDir = "session"] =
process.argv.slice(2);
if (!textFilePath) {
console.error("Error: textFilePath is required");
process.exit(1);
}
if (!voiceId) {
console.error("Error: voiceId is required");
process.exit(1);
}
// Read text from file
if (!fs.existsSync(textFilePath)) {
console.error(`Error: file not found: ${textFilePath}`);
process.exit(1);
}
const text = fs.readFileSync(textFilePath, "utf-8").trim();
if (!text) {
console.error("Error: file is empty");
process.exit(1);
}
async function main() {
const url = `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}?output_format=${outputFormat}`;
console.log(`Reading text from: ${textFilePath}`);
console.log(`Text preview: "${text.substring(0, 50)}${text.length > 50 ? "..." : ""}"`);
console.log(`Voice ID: ${voiceId}`);
console.log(`Model: ${modelId}`);
console.log(`Characters: ${text.length}`);
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();
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);
});