0
Create speech
One script reply has been approved by the moderators Verified

Generates audio from the input text.

Created by hugo697 136 days ago Viewed 3760 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 136 days ago
1
type Openai = {
2
  api_key: string;
3
  organization_id: string;
4
};
5
/**
6
 * Create speech
7
 * Generates audio from the input text.
8
 */
9
export async function main(
10
  auth: Openai,
11
  body: {
12
    model: string | ("tts-1" | "tts-1-hd");
13
    input: string;
14
    voice: "alloy" | "echo" | "fable" | "onyx" | "nova" | "shimmer";
15
    response_format?: "mp3" | "opus" | "aac" | "flac" | "wav" | "pcm";
16
    speed?: number;
17
  }
18
) {
19
  const url = new URL(`https://api.openai.com/v1/audio/speech`);
20

21
  const response = await fetch(url, {
22
    method: "POST",
23
    headers: {
24
      "OpenAI-Organization": auth.organization_id,
25
      "Content-Type": "application/json",
26
      Authorization: "Bearer " + auth.api_key,
27
    },
28
    body: JSON.stringify(body),
29
  });
30
  if (!response.ok) {
31
    const text = await response.text();
32
    throw new Error(`${response.status} ${text}`);
33
  }
34
  return await response.text();
35
}
36