Files
anything-llm/server/utils/TextToSpeech/elevenLabs/index.js
Marcello Fitton 4a4378ed99 chore: add ESLint to /server (#5126)
* add eslint config to server

* add break statements to switch case

* add support for browser globals and turn off empty catch blocks

* disable lines with useless try/catch wrappers

* format

* fix no-undef errors

* disbale lines violating no-unsafe-finally

* ignore syncStaticLists.mjs

* use proper null check for creatorId instead of unreachable nullish coalescing

* remove unneeded typescript eslint comment

* make no-unused-private-class-members a warning

* disable line for no-empty-objects

* add new lint script

* fix no-unused-vars violations

* make no-unsued-vars an error

---------

Co-authored-by: shatfield4 <seanhatfield5@gmail.com>
Co-authored-by: Timothy Carambat <rambat1010@gmail.com>
2026-03-05 16:32:45 -08:00

55 lines
1.4 KiB
JavaScript

const { ElevenLabsClient } = require("elevenlabs");
class ElevenLabsTTS {
constructor() {
if (!process.env.TTS_ELEVEN_LABS_KEY)
throw new Error("No ElevenLabs API key was set.");
this.elevenLabs = new ElevenLabsClient({
apiKey: process.env.TTS_ELEVEN_LABS_KEY,
});
// Rachel as default voice
// https://api.elevenlabs.io/v1/voices
this.voiceId =
process.env.TTS_ELEVEN_LABS_VOICE_MODEL ?? "21m00Tcm4TlvDq8ikWAM";
this.modelId = "eleven_multilingual_v2";
}
static async voices(apiKey = null) {
try {
const client = new ElevenLabsClient({
apiKey: apiKey ?? process.env.TTS_ELEVEN_LABS_KEY ?? null,
});
return (await client.voices.getAll())?.voices ?? [];
} catch {}
return [];
}
#stream2buffer(stream) {
return new Promise((resolve, reject) => {
const _buf = [];
stream.on("data", (chunk) => _buf.push(chunk));
stream.on("end", () => resolve(Buffer.concat(_buf)));
stream.on("error", (err) => reject(err));
});
}
async ttsBuffer(textInput) {
try {
const audio = await this.elevenLabs.generate({
voice: this.voiceId,
text: textInput,
model_id: "eleven_multilingual_v2",
});
return Buffer.from(await this.#stream2buffer(audio));
} catch (e) {
console.error(e);
}
return null;
}
}
module.exports = {
ElevenLabsTTS,
};