-
Notifications
You must be signed in to change notification settings - Fork 65
/
tts.js
98 lines (85 loc) · 2.72 KB
/
tts.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
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
95
96
97
98
var querystring = require('querystring');
var got = require('got');
var fs = require('fs');
var token = require('./token');
var languages = require('./languages');
// copy from https://github.com/zlargon/google-tts/blob/master/example/long-english-characters.js
// todo: could be optimized
function split(text) {
const MAX = 200; // Max string length
const isSpace = (s, i) => /\s/.test(s.charAt(i));
const lastIndexOfSpace = (s, left, right) => {
for (let i = right; i >= left; i--) {
if (isSpace(s, i)) return i;
}
return -1; // not found
};
const result = [];
const addResult = (text, start, end) => {
const str = text.slice(start, end + 1);
result.push(str);
};
let start = 0;
for (; ;) {
// check text's length
if (text.length - start <= MAX) {
addResult(text, start, text.length - 1);
break; // end of text
}
// check whether the word is cut in the middle.
let end = start + MAX - 1;
if (isSpace(text, end) || isSpace(text, end + 1)) {
addResult(text, start, end);
start = end + 1;
continue;
}
// find last index of space
end = lastIndexOfSpace(text, start, end);
if (end === -1) {
throw new Error('the amount of single word is over that 200.');
}
// add result
addResult(text, start, end);
start = end + 1;
}
return result;
}
function multi(arr, opts) {
return single(arr.shift(), opts).then(function () {
if (arr.length > 0) return multi(arr, opts);
});
}
function single(text, opts) {
opts = opts || {};
return token.get(text, opts).then(function (token) {
var url = opts.domain + '/translate_tts';
var data = {
client: opts.client || 't',
tl: opts.to,
ie: 'UTF-8',
idx: 0,
total: 1,
textlen: text.length,
q: text
};
data[token.name] = token.value;
return url + '?' + querystring.stringify(data);
}).then(function (url) {
return got(url, {encoding: null, agent: opts.agent}).then(function (res) {
fs.appendFile(opts.file, res.body, function (err) {
if (err) throw err;
});
}).catch(function (err) {
err.message += `\nUrl: ${url}`;
if (err.statusCode !== undefined && err.statusCode !== 200) {
err.code = 'BAD_REQUEST';
} else {
err.code = 'BAD_NETWORK';
}
throw err;
});
});
}
module.exports.single = single;
module.exports.multi = multi;
module.exports.split = split;