route.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. export async function POST(req: Request) {
  2. const { text, voiceId } = await req.json();
  3. const apiKey = process.env.ELEVENLABS_API_KEY;
  4. if (!apiKey) {
  5. return new Response(
  6. JSON.stringify({ error: "ELEVENLABS_API_KEY not set" }),
  7. {
  8. status: 500,
  9. headers: { "Content-Type": "application/json" },
  10. },
  11. );
  12. }
  13. const voice = voiceId || "21m00Tcm4TlvDq8ikWAM";
  14. const response = await fetch(
  15. `https://api.elevenlabs.io/v1/text-to-speech/${voice}`,
  16. {
  17. method: "POST",
  18. headers: {
  19. "xi-api-key": apiKey,
  20. "Content-Type": "application/json",
  21. },
  22. body: JSON.stringify({
  23. text,
  24. model_id: "eleven_monolingual_v1",
  25. voice_settings: {
  26. stability: 0.5,
  27. similarity_boost: 0.75,
  28. },
  29. }),
  30. },
  31. );
  32. if (!response.ok) {
  33. return new Response(JSON.stringify({ error: "TTS generation failed" }), {
  34. status: 500,
  35. headers: { "Content-Type": "application/json" },
  36. });
  37. }
  38. const audioBuffer = await response.arrayBuffer();
  39. return new Response(audioBuffer, {
  40. headers: {
  41. "Content-Type": "audio/mpeg",
  42. "Cache-Control": "public, max-age=3600",
  43. },
  44. });
  45. }