forked from pot-app/pot-app-tts-plugin-openai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
60 lines (57 loc) · 1.31 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
async function tts(text, _lang, options = {}) {
const { config, utils } = options;
const { http } = utils;
const { fetch, Body } = http;
let { requestPath, apiKey, model, voice, speed } = config;
if (!requestPath) {
requestPath = "https://api.openai.com";
}
if (!/https?:\/\/.+/.test(requestPath)) {
requestPath = `https://${requestPath}`;
}
if (requestPath.endsWith("/")) {
requestPath = requestPath.slice(0, -1);
}
if (!requestPath.endsWith("/audio/speech")) {
requestPath += "/v1/audio/speech";
}
if (!apiKey) {
throw "apiKey is required";
}
if (!model) {
model = "tts-1";
}
if (!voice) {
voice = "alloy";
}
if (!speed) {
speed = 1.0;
}
const safeText = text.trim().normalize("NFKC");
const res = await fetch(requestPath, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
Authorization: `Bearer ${apiKey}`,
},
body: Body.json({
model,
voice,
speed: parseFloat(speed),
input: safeText,
}),
responseType: 3,
});
if (res.ok) {
let result = res.data;
if (result) {
return result;
} else {
throw JSON.stringify(result);
}
} else {
throw `Http Request Error\nHttp Status: ${res.status}\n${JSON.stringify(
res.data
)}`;
}
}