一、预热:先看两个主要的接口

1.获取token的接口 https://openapi.baidu.com/oauth/2.0/token

2.语音合成接口  http://tsn.baidu.com/text2audio 或 https://tsn.baidu.com/text2audio

二、开通百度语音接口,创建应用获取密钥信息

https://console.bce.baidu.com/ai/?_=1533186278816#/ai/speech/app/list

三、新建小程序

1.先写好小程序页面,通过可视化操作获取接口参数

2.写获取token的方法,并在小程序加载时调用

 onLoad() {    that = this;    that.getToken();  },  getToken() {    //先看下缓存里有没有token    var token = wx.getStorageSync('token');    var token_expire = wx.getStorageSync('token_expire');    //如果缓存里没有或者说过了有效期的话重新获取token    if (!token || token_expire <= new Date().getTime()) {      //这个要换成自己的apikey和secretkey!!!!!      let api_key = 'BUYAOFUZHIZHEGESHIJIADE';      let secret_key = 'ZHegEDAngrAnyEShIjIaDEShABi';      var url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + api_key + "&client_secret=" + secret_key;      wx.request({        url: url,        success: e => {          //保存获取到的token及有效时间            token = e.data.access_token;          token_expire = e.data.expires_in * 1000 + new Date().getTime();          wx.setStorageSync('token', token);          wx.setStorageSync('token_expire', token_expire);          that.setData({            token: token          })        },        fail() {          ws.showToast({            'title': '哎呀,你断网了吧',          });        },        complete() {          wx.hideLoading();        }      })    } else {      that.setData({        token: token      })    }  }

3.表单提交时播放语音

 submit(e){    //获取表单数据    let data = e.detail.value;    //拼接参数    data['tok'] = that.data.token;    //随机id    data['cuid'] = 'txx_xcx';    data['lan'] = 'zh';    data['ctp'] = 1;        if (!data['tex']) {      data['tex'] = 'txx真他喵的帅';    }    //数组转字符    let arr = [];    for(var x in data){      arr.push(x+'='+data[x]);    }    let str = arr.join('&');    //ad是一开始定义的音频常量 const ad = wx.createInnerAudioContext();    //修改网址    ad.src = encodeURI('https://tsn.baidu.com/text2audio?' + str);    //然后播放    ad.play();  },

完整代码:https://download.csdn.net/download/txx_c/10741505

记得改apikey和secretkey

TAG标签: 微信小程序怎么转发语音

http://www.xiaochengxub.com/read-99680.html