一、微信小程序后台启用插件
二、微信小程序配置文件
在项目app.json中添加以下内容
"plugins": {
"WechatSI": {
"version": "0.3.5",
"provider": "wx069ba97219f66d99"
}
}
三、小程序页面调用插件播放语音
在需要播放语音的页面添加相关的代码,为提升播放效率,相关的播放内容将缓存起来,已播放过的内容直接调用缓存直接播放,否则从网络中请求新的语音数据。
//引入插件:微信同声传译
const plugin = requirePlugin('WechatSI');
//获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager();
onLoad: function(options) {
//创建内部 audio 上下文 InnerAudioContext 对象。
this.innerAudioContext = wx.createInnerAudioContext();
this.innerAudioContext.onError(function (res) {
console.log(res);
wx.showToast({
title: '语音播放失败',
icon: 'none',
})
})
this.wordYun("查无订餐记录", function() {
that.setData({
loadingFlag: !1
})
})
},
// 文字转语音
wordYun: function(e, cb) {
var that = this;
var content = e;
var t_file = wx.getStorageSync(e)
console.log(t_file)
if (t_file) {
console.log("文件播放")
that.innerAudioContext.src = t_file
that.innerAudioContext.play(); //播放音频
} else {
console.log("网络播放")
plugin.textToSpeech({
lang: "zh_CN",
tts: true,
content: content,
success: function(res) {
console.log(res);
console.log("succ tts", res.filename);
that.setData({
src: res.filename
})
wx.downloadFile({
url: res.filename,
success: function(res) {
let path = res.tempFilePath
console.log("my path")
console.log(path)
that.innerAudioContext.src = path
that.innerAudioContext.play(); //播放音频
wx.setStorage({
key: e,
data: path,
})
// wx.saveFile({
// tempFilePath: path,
// success(res) {
// var savedFilePath = res.savedFilePath;
// },
// }
}
})
// that.innerAudioContext.src = res.filename
// that.innerAudioContext.play(); //播放音频
typeof cb == "function" && cb()
},
fail: function(res) {
console.log("fail tts", res)
}
})
}
},