-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmod.ts
71 lines (61 loc) · 1.59 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
import { writeAll } from "./deps.ts";
import { LANGUAGES } from "./src/languages.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 SaveOptions {
language: keyof typeof LANGUAGES;
}
/**
* 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<SaveOptions>,
) {
const config: SaveOptions = {
...{
language: "en-us",
},
...options,
};
const textParts = tokenize(text);
try {
await Deno.remove(path);
} catch {
// swallow error
}
const file = await Deno.open(path, {
create: true,
append: true,
write: true,
});
for (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;
const req = await fetch(url, {
headers,
});
const buffer = await req.arrayBuffer();
const data = new Uint8Array(buffer);
await writeAll(file, data);
}
file.close();
}