想着既然自己踩了几天坑解决了问题,那就花点时间整理给有需要的人,这样社区有用的帖子才会越来越多。
一 问题背景
微信小程序端需要解决语音识别的功能。
二 思路
当时的思路有一个,就是使用小程序的录音和上传api,将录音文件上传到后台,后台调用第三方语音接口将识别的内容再返回给小程序,这样实现我觉得应该也可以。但是百度发现了小程序的团队开发的第三方插件,试了一下可以用。
三 实现方法
1登陆小程序管理后台,设置->第三方设置(拖到下方插件管理)->添加插件->搜索“同声传译”
![](http://img-cdn-tc.dcloud.net.cn/uploads/article/20190902/beef8afbb8a7fbd941038f5102e51f70.png)
2在manifest.json文件中,小程序节点下添加插件。
"mp-weixin" : {
/* 小程序特有相关 */
"appid" : "wx59f6366a9db5ced5",
"setting" : {
"urlCheck" : true
},
"usingComponents" : true,
"plugins" : {
"WechatSI" : {
"version" : "0.3.1",
"provider" : "wx069ba97219f66d99"
}
}
},
3在功能页面中使用就可以了
<template>
<view>
<!-- #ifndef H5 -->
<cu-custom bgColor="bg-gradual-green">
<block slot="content">语音识别</block>
</cu-custom>
<!-- #endif -->
<view class="voicepad">
{{voiceState}}
</view>
<button class="cu-btn bg-green voicebtn " @touchstart="touchStart" @touchend="touchEnd"><text class="cuIcon-voicefill"></text></button>
</view>
</template>
<script>
var plugin = requirePlugin("WechatSI")
let manager = plugin.getRecordRecognitionManager();
export default {
data() {
return {
voiceState: "你可以这样说..."
}
},
onShow() {
},
onLoad() {
this.initRecord();
},
methods: {
touchStart: function() {
// uni.vibrateLong({
// success:function(){
// }
// });
manager.start({
duration: 60000,
lang: "zh_CN"
});
},
touchEnd: function() {
uni.showToast()
manager.stop();
},
/**
* 初始化语音识别回调
* 绑定语音播放开始事件
*/
initRecord: function() {
manager.onStart = function(res) {
this.voiceState ="onStart:"+ res.msg+"正在录音"
};
//有新的识别内容返回,则会调用此事件
manager.onRecognize = (res) => {
this.voiceState = "onRecognize"+res.result;
}
// 识别结束事件
manager.onStop = (res) => {
this.voiceState ="onStop"+ res.result;
}
// 识别错误事件
manager.onError = (res) => {
this.voiceState = "onError"+res.msg;
}
},
}
}
</script>
<style>
.voicebtn{height:130upx;display: block;width:130upx;line-height:130upx;border-radius: 65upx;font-size: 50upx;position: absolute;top:1060upx;left:310upx;}
.voicepad{height: 250upx;width:680upx;background: #fff;margin: 30upx auto;border-radius: 8upx;color: #CCCCCC;padding:20upx;font-size: 35upx;}
</style>