elevenlabs.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { TalkStyle } from "@/features/chat/messages";
  2. import { TTSBackend } from "@/types/backend";
  3. export async function elevenlabs(
  4. config: TTSBackend["elevenlabs"],
  5. message: string,
  6. voiceId: string,
  7. ) {
  8. const apiKey = config?.elevenlabs_apikey;
  9. if (! apiKey) {
  10. throw new Error("Invalid ElevenLabs API Key");
  11. }
  12. // Request body
  13. const body = {
  14. text: message,
  15. model_id: config?.elevenlabs_model,
  16. voice_settings: {
  17. stability: 0,
  18. similarity_boost: 0,
  19. style: 0,
  20. use_speaker_boost: true
  21. }
  22. };
  23. const elevenlabsRes = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}?optimize_streaming_latency=0&output_format=mp3_44100_128`, {
  24. method: "POST",
  25. body: JSON.stringify(body),
  26. headers: {
  27. "Content-Type": "application/json",
  28. "Accept": "audio/mpeg",
  29. "xi-api-key": apiKey,
  30. },
  31. });
  32. if (! elevenlabsRes.ok) {
  33. throw new Error(`ElevenLabs API Error (${elevenlabsRes.status})`);
  34. }
  35. const data = (await elevenlabsRes.arrayBuffer()) as any;
  36. return { audio: data };
  37. }