Skip to content

Instantly share code, notes, and snippets.

@maicong
Created June 15, 2017 09:45
Show Gist options
  • Select an option

  • Save maicong/03f71a964ef2529135ab9bb515eb107e to your computer and use it in GitHub Desktop.

Select an option

Save maicong/03f71a964ef2529135ab9bb515eb107e to your computer and use it in GitHub Desktop.
/**
* 安装
* yarn add babel-cli babel-preset-env axios qs
*
* 配置 .babelrc
* {
* "presets": ["env"]
* }
*
* 运行
* node_modules/.bin/babel-node nodeTTS.js
*/
const axios = require('axios')
const qs = require('qs')
const Player = require('player') // 不存在的
const getAudio = async text => {
return axios({
method: 'post',
url: 'https://ai.baidu.com/aidemo',
data: qs.stringify({
type: 'tts',
speed: 5,
vol: 6,
person: 4,
text: text
}),
timeout: 10000,
headers: {
Origin: 'https://ai.baidu.com',
Referer: 'https://ai.baidu.com/tech/speech/tts',
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3087.0 Safari/537.36',
Cookie: 'BDUSS=pOSTBKcEtpY0pZYkJEdnZPMEFTdVExZGpUbTlneTI1TDFlT2taM3JPWGpNV2haSVFBQUFBJCQAAAAAAAAAAAEAAADXIkATwvPM79K7uPm00AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOOkQFnjpEBZbn'
}
}).then(r => r.data.data)
}
const text = '当不幸降临在他人头上时,他们往往都能像智者一样劝慰别人;而当同样的不幸降临自己身上时,人往往很难同样地开导自己。人最大的不智不是不知道,而是知道了却迟迟不愿去做,所以平庸却又自怜的人很多。'
const textArr = text
.replace(/(;|。|\n|\r)/g, '__line__')
.split('__line__')
.filter(v => {
return /[A-Za-z0-9\u3000\u3400-\u4DBF\u4E00-\u9FFF]+/i.test(v)
})
const loop = async i => {
const mp3 = await getAudio(textArr[i])
if (mp3) {
const audio = new Player(mp3)
audio.play()
audio.on('playend', () => {
console.log(i, 'play done, switching to next one ...')
loop(i++)
})
}
}
loop(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment