npm i @alicloud/pop-core -S
实例化客户端
// 官方文档:https://help.aliyun.com/document_detail/72153.html?spm=a2c4g.94737.0.0.2457323fp1TvWy#554cde703a4xl
const RPCClient = require('@alicloud/pop-core').RPCClient
const ttsClient = new RPCClient({
accessKeyId: 'xxx', // 阿里云申请
accessKeySecret: 'xxx', // 阿里云申请
endpoint: 'http://nls-meta.cn-shanghai.aliyuncs.com/',
apiVersion: '2019-02-28'
})
Copy
接口
router.get('/get/tts/url', async (req, res) => {
// 获取token
// 官方文档:https://help.aliyun.com/document_detail/72153.html?spm=a2c4g.94737.0.0.2457323fp1TvWy#554cde703a4xl
let token;
if(req.cookies.tts_token) {
token = req.cookies.tts_token
} else {
const result = await ttsClient.request('CreateToken')
if(result.ErrCode) {
console.error(result)
} else {
token = result.Token.Id
res.cookie('tts_token', token, { expires: new Date(result.Token.ExpireTime * 1000) })
}
}
// RESTful API
// 官方文档:https://help.aliyun.com/document_detail/94737.html?spm=a2c4g.450255.0.0.3d044919tDgkvd
const url = `https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts?appkey=xxx&token=${token}&text=${req.query.text}&format=wav&sample_rate=16000&voice=aida`
// 转换成音频输出
https.get(url, (response) => {
res.setHeader('Content-Type', 'audio/mpeg')
response.pipe(res)
})
})
Copy
前端调用
const ttsAudio = new Audio()
ttsAudio.src = `http://localhost/get/tts/url?text=${encodeURI('你好,世界')}`
ttsAudio.play()
ttsAudio.onended = function () {
// ...
}