赞
踩
npm i @alicloud/pop-core -S
- // 官方文档:SDK方式获取Token_智能语音交互(ISI)-阿里云帮助中心
- 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
- // 官方文档:SDK方式获取Token_智能语音交互(ISI)-阿里云帮助中心
- 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
- // 官方文档:语音合成RESTfulAPI_智能语音交互(ISI)-阿里云帮助中心
- 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 () {
- // ...
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。