-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
44 lines (38 loc) · 923 Bytes
/
index.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
var request = require('request')
module.exports = function(text, lang, cb){
var isFunc = typeof lang === 'function';
cb = isFunc ? lang : cb;
if(!lang || isFunc) {
lang = detectLang(text);
}
// fix empty text
// for a 1K empty voice
//if (!text) text = ' '
// throw for empty text
if (!text) {
return cb(new Error('empty text'))
}
// fetches voice
request({
url: getUrl(text, lang),
encoding: null // for buffer
}, function(err, res, buf){
if (err) return cb(err)
if (!/^audio\//.test(res.headers['content-type'])) {
return cb(new Error('no audio'))
}
cb(null, buf)
})
}
function detectLang(text) {
return /^[a-z]/i.test(text) ? 'en' : 'zh-CN';
}
function getUrl(text, lang){
// build google url
var url = [
'http://translate.google.cn/translate_tts?ie=UTF-8&q=',
encodeURIComponent(text),
'&tl=' + lang
].join('')
return url
}