背景
公司一个餐饮项目小程序,需要管理端小程序循环扫码核销用餐二维码,这样可以固定手机然后核销,解放核销阿姨的双手,工作效率提高,但是发现阿姨又老是要去看手机提示核销成功后,再给用户发餐,觉得还不行,于是想出小程序语音提示核销成功,这里我就用了这个微信官方的【同声传译】插件,将指定文字转换成语音,从而实现语音提示。彻底提升了核销阿姨的工作效率!!!
不要问为什么不买个核销机,问就是公司抠门,不打算出钱,我又是现成牛马,让我开发就完事了!!!
准备工作
1、打开小程序管理端,依次点击【设置】-【第三方设置】-【插件管理】,然后点击【添加插件】。
2、搜索【微信同声传译】,然后点击【添加】。
3、添加完成后,点击插件右侧的【详情】,然后记录下【appid】和【版本号】两个参数。
4、在小程序代码的【app.json】文件中 添加如下配置,用以引入插件,到这里准备工作就完成了,可以去实现我们的功能了!
"plugins":{
"WechatSI": {
"version": "0.3.6",
"provider":"wx069ba97219f66d99"
}
}
代码实现
最后附有完整功能源码,如果不想一步步来,可以直接到最后去复制。
1、效果页面引入【同声传译】插件。
//引入插件:微信同声传译
const plugin = requirePlugin('WechatSI');
Page({
......
})
2、设置两个参数,一个是需要提示的文字内容content,一个是转换成语音后的路径src。
Page({
data: {
content: '', // 语音提示内容
src: '', // 转换成语音后的路径
}
})
3、在onReady中创建【InnerAudioContext】对象,用于播放语音,并监听播放失败事件。
onReady(e) {
// 创建内部 audio 上下文 InnerAudioContext 对象。
this.innerAudioContext = wx.createInnerAudioContext();
// 监测语音播放失败事件
this.innerAudioContext.onError(function (res) {
console.log(res);
wx.showToast({
title: '语音播放失败',
icon: 'error',
duration: 2000
})
})
}
4、实现文字转语音,以及控制播放和结束。
// 文字转语音
wordToVoice:function (e) {
var that = this;
var content = this.data.content;
// 实现转换
plugin.textToSpeech({
lang: "zh_CN", // 识别的语言,目前支持zh_CN en_US zh_HK sichuanhua
tts: true, // 是否进行语音合成
content: content, // 识别的文本
success: function (res) {
console.log("转换成功:", res.filename);
that.setData({
src: res.filename
})
that.voicePlay(); // 播放语音
},
fail: function (res) {
console.log("转换失败:", res)
}
})
},
//播放语音
voicePlay: function (e) {
if (this.data.src == '') {
console.log('暂无语音');
return;
}
this.innerAudioContext.src = this.data.src // 设置音频地址
this.innerAudioContext.play(); // 播放音频
},
// 结束语音
voicePlayEnd: function (e) {
this.innerAudioContext.pause(); // 暂停音频
},
5、现在你只用给content参数赋值你想要转换的文本,然后调用wordToVoice()方法即可实现语音提示!!!
完整源码
//引入插件:微信同声传译
const plugin = requirePlugin('WechatSI');
Page({
data: {
content: '', // 语音提示内容
src: '', // 转换成语音后的路径
},
onReady(e) {
// 创建内部 audio 上下文 InnerAudioContext 对象。
this.innerAudioContext = wx.createInnerAudioContext();
// 监测语音播放失败事件
this.innerAudioContext.onError(function (res) {
console.log(res);
wx.showToast({
title: '语音播放失败',
icon: 'error',
duration: 2000
})
})
},
// 文字转语音
wordToVoice:function (e) {
var that = this;
var content = this.data.content;
// 实现转换
plugin.textToSpeech({
lang: "zh_CN", // 识别的语言,目前支持zh_CN en_US zh_HK sichuanhua
tts: true, // 是否进行语音合成
content: content, // 识别的文本
success: function (res) {
console.log("转换成功:", res.filename);
that.setData({
src: res.filename
})
that.voicePlay(); // 播放语音
},
fail: function (res) {
console.log("转换失败:", res)
}
})
},
//播放语音
voicePlay: function (e) {
if (this.data.src == '') {
console.log('暂无语音');
return;
}
this.innerAudioContext.src = this.data.src // 设置音频地址
this.innerAudioContext.play(); // 播放音频
},
// 结束语音
voicePlayEnd: function (e) {
this.innerAudioContext.pause(); // 暂停音频
}
})