forked from dunosaurs/gtts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
94 lines (83 loc) · 2.22 KB
/
mod.ts
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import type { LANGUAGES } from "./src/languages.ts";
import { writeAll } from "./deps.ts";
const GOOGLE_TTS_URL = "http://translate.google.com/translate_tts";
const headers = {
"User-Agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.17 (KHTML like Gecko) Version/6.0.2 Safari/536.26.17",
};
function tokenize(text: string) {
return text
.split(/¡|!|\(|\)|\[|\]|\¿|\?|\.|\,|\;|\:|\—|\«|\»|\n/)
.filter((p) => p);
}
/**
* The options for TTS
*/
export interface Options {
language: keyof typeof LANGUAGES;
}
/**
* Convert text to speech and save to a .wav file
* @example
* ```typescript
* await gtts("hello text to speech", { language: "en-us" });
* ```
*/
export default async function gtts(
text: string,
options?: Partial<Options>
): Promise<Uint8Array> {
const { resolve, reject, promise } = Promise.withResolvers<Uint8Array>();
const config: Options = {
...{
language: "en-us",
},
...options,
};
const textParts = tokenize(text);
const chunks: Uint8Array[] = [];
for await (const [i, part] of Object.entries(textParts)) {
const encodedText = encodeURIComponent(part);
const args = `?ie=UTF-8&tl=${config.language}&q=${encodedText}&total=${textParts.length}&idx=${i}&client=tw-ob&textlen=${encodedText.length}`;
const url = GOOGLE_TTS_URL + args;
try {
const req = await fetch(url, {
headers,
});
const buffer = await req.arrayBuffer();
const data = new Uint8Array(buffer);
chunks.push(data);
} catch (e) {
reject(e);
}
}
const buffer = new Blob(chunks, { type: "audio/wav" });
resolve(new Uint8Array(await buffer.arrayBuffer()));
return promise;
}
/**
* Convert text to speech and save to a .wav file
* @example
* ```typescript
* await save("./demo.wav", "hello text to speech", { language: "en-us" });
* ```
*/
export async function save(
path: string,
text: string,
options?: Partial<Options>
): Promise<void> {
try {
await Deno.remove(path);
} catch {
// swallow error
}
const data = await gtts(text, options);
const file = await Deno.open(path, {
create: true,
append: true,
write: true,
});
await writeAll(file, data);
file.close();
}