openaiTTS.ts 903 B

123456789101112131415161718192021222324252627282930313233343536
  1. import { TTSBackend } from "@/types/backend";
  2. export async function openaiTTS(
  3. config: TTSBackend["openai_tts"],
  4. message: string,
  5. ) {
  6. const apiKey = config?.openai_tts_apikey;
  7. if (!apiKey) {
  8. throw new Error("Invalid OpenAI TTS API Key");
  9. }
  10. try {
  11. const res = await fetch(`${config.openai_tts_url}/v1/audio/speech`, {
  12. method: "POST",
  13. body: JSON.stringify({
  14. model: config.openai_tts_model,
  15. input: message,
  16. voice: config.openai_tts_voice,
  17. }),
  18. headers: {
  19. "Content-Type": "application/json",
  20. "Authorization": `Bearer ${apiKey}`,
  21. },
  22. });
  23. if (! res.ok) {
  24. console.error(res);
  25. throw new Error("OpenAI TTS API Error");
  26. }
  27. const data = (await res.arrayBuffer()) as any;
  28. return { audio: data };
  29. } catch (e) {
  30. console.error('ERROR', e);
  31. throw new Error("OpenAI TTS API Error");
  32. }
  33. }