小程序调用百度TTS语音合成接口
这次小程序改版,要将服务器推送到小程序的消息,由文字转换成语音,进行播放。
因为是第一次接触,所以做了一个简单的测试。
看百度百度TTS文档
【1】先看接入指南:http://ai.baidu.com/docs#/Begin/top
按照接入指南上来操作,通过百度云直接登录后台,AI相关服务模块入口,则如下图红框部分所示:

【2】再看语音合成:http://ai.baidu.com/docs#/TTS-API/top
文档上说要先在您创建的应用中查找Api Key 和 SecretKey。
访问https://openapi.baidu.com/oauth/2.0/token 换取 token

【3】访问合成接口 https://openapi.baidu.com/oauth/2.0/token?

【4】知道音频地址后就可以播放

整个测试代码如下:
【1 index.wxml】

【2 index.js】
因为是测试websocket推送消息成功后,接收到的数据,进行语音合成。




var msg, token, IMEI, filePath
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that=this
wx.getSystemInfo({
success: function (res) {
console.log(res)
IMEI = res.SDKVersion
console.log(IMEI)
}
}) ,
//建立连接
wx.connectSocket({
url: "ws://123.207.167.163:9010/ajaxchattest",
success:function(res){
console.log(res)
}
})
var socketOpen = false
var socketMsgQueue = []
//连接成功监听WebSocket连接打开事件。
wx.onSocketOpen(function () {
console.log("-----连接成功")
socketOpen = true
that.sendMessage(msg)
})
//监听WebSocket接受到服务器的消息事件接收数据
wx.onSocketMessage(function (res) {
msg=res.data;
console.log('接收数据----', msg);
var contact = JSON.parse(msg);
that.setData({
msg: contact.msg
})
})
//连接失败
wx.onSocketError(function () {
console.log('websocket连接失败!');
})
},
sendMessage: function (msg) {
msg="您好,欢迎光临";
var data = {
msg: msg
}
wx.sendSocketMessage({
data: JSON.stringify(data),
success: function (res) {
console.log(res)
}
})
},
tts:function(e){
var grant_type ="client_credentials";
var appKey ="7A6fuVBxIgjCCMu0eMhsxyuu";
var appSecret ="HMxdXoT0FCGWSkgiCZQclcoHBswYyP0p";
// var url = "https://openapi.baidu.com/oauth/2.0/token" + "grant_type=" + grant_type + "&client_id=" + appKey + "&client_secret=" + appSecret
var url = "https://openapi.baidu.com/oauth/2.0/token"
wx.request({
url: url,
data: {
grant_type: grant_type,
client_id: appKey,
client_secret: appSecret
},
method: "GET",
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
console.log(res.data)
token = res.data.access_token
}
})
},
// 合成
cancel: function (e) {
var text = JSON.parse(msg).msg;
var tex = encodeURI(text);//转换编码url_encode UTF8编码
var tok = token;
var cuid = IMEI;
var ctp=1;
var lan = "zh"; // zh表示中文
// 字符编码
var spd = 5; // 表示朗读的语速,9代表最快,1是最慢(撩妹请用2,绕口令请用9)
var url = "https://tsn.baidu.com/text2audio?tex=" + tex + "&lan=" + lan + "&cuid=" + cuid + "&ctp=" + ctp + "&tok=" + tok + "&spd=" +spd
wx.downloadFile({
url: url,
success: function (res) {
console.log(res)
filePath=res.tempFilePath;
// 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
if (res.statusCode === 200) {
wx.playVoice({
filePath: res.tempFilePath
})
}
}
})
},
//播放
play: function (e) {
const innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.autoplay = true
innerAudioContext.src = filePath
innerAudioContext.onPlay(() => {
console.log('开始播放')
})
innerAudioContext.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
})
},
})