开发背景
小程序需求需要一个用户语音输入的组件,实现用户语音简便输入。
前期准备
在小程序后台设置里面第三方设置添加同声传译插件
插件介绍
微信同声传译插件是微信自研的语音输入,文本翻译等功能的插件封装,用于提供给第三方小程序调用。
微信面对面翻译小程序完全使用此小程序插件实现。开源地址:github.com/Tencent/Fac…
语音输入
先引入同声传译然后定义变量
const plugin = requirePlugin("WechatSI")
const voicManager = plugin.getRecordRecognitionManager()
在框架生命周期进行同声传译插件初始化
const initRecord = () => {
// 有新的识别内容返回,则会调用此事件
voicManager.onRecognize = function (res: any) {
console.log(res, "new")
}
// 正常开始录音识别时会调用此事件
voicManager.onStart = function (res: any) {
console.log("成功开始录音识别", res)
//runing检测是否语音正在转译中,如果正在转译则不让他再次进入语音输入
runing.value = true
distance.value = 0
}
// 识别错误事件
voicManager.onError = function (res: any) {
console.log(res)
runing.value = false
const tips = {
"-30003": "未识别出文字",
"-30004": "未识别出文字",
"-30006": "录音超时",
}
const retcode: string = res?.retcode.toString()
retcode &&
uni.showToast({
title: tips[retcode],
icon: "none",
duration: 2000,
})
}
//识别结束事件
voicManager.onStop = function (res: {
tempFilePath: string
duration: string
fileSize: string
result: string
}) {
console.log(res.result, "stop")
finnlResult.value += res.result
runing.value = false
// console.log("..............结束录音", res)
// console.log("录音临时文件地址 -->", res.tempFilePath)
// console.log("录音总时长 -->", res.duration, "ms")
// console.log("文件大小 --> ", res.fileSize, "B")
// console.log("语音内容 --> ", res.result)
if (res.result === "") {
uni.showModal({
title: "提示",
content: "没有听清,请再说一次~",
showCancel: false,
})
return
}
}
}
语音授权:在使用之前获取权限,如果第一次拒绝了第二次直接进入微信小程序设置授权页面
const becomeVoice = () => {
uni.authorize({
scope: "scope.record",
fail: () => {
// 进入微信小程序设置授权界面
uni.getSetting({
success: (res) => {
if (res.authSetting["scope.record"]) {
currentStatus.value = 1
} else {
showGetRecord.value = true
}
},
})
},
})
}
文本翻译
plugin.translate({
lfrom:"en_US",
lto:"zh_CN",
content:"hello, this is the first time to test?",
success: function(res) {
if(res.retcode == 0) {
console.log("result", res.result)
} else {
console.warn("翻译失败", res)
}
},
fail: function(res) {
console.log("网络失败",res)
}
})