需求
小程序錄制聲音,翻譯成中文。
小程序組件地址:鏈接: https://mp.weixin.qq.com/wxopen/pluginbasicprofile?action=intro&appid=wx069ba97219f66d99&token=&lang=zh_CN.
微信同聲傳譯插件是微信自研的語音輸入,文本翻譯等功能的插件封裝,用於提供給第三方小程序調用。
微信面對面翻譯小程序完全使用此小程序插件實現。開源地址:
鏈接: https://github.com/Tencent/Face2FaceTranslator.
小程序代碼
使用前,需要在小程序設置中添加第三方插件“微信同聲傳譯”
插件說明:鏈接: https://developers.weixin.qq.com/community/develop/doc/0004aa70d609e099c1d671b2a56009.
app.json 引入插件
"plugins": {
"WechatSI": {
"version": "0.0.6",
"provider": "wx069ba97219f66d99"
}
},
**app.js 權限詢問(可寫在其他頁面中) **
// 權限詢問
getRecordAuth: function () {
wx.getSetting({
success(res) {
console.log("succ")
console.log(res)
if (!res.authSetting['scope.record']) {
wx.authorize({
scope: 'scope.record',
success() {
// 用戶已經同意小程序使用錄音功能,後續調用 wx.startRecord 接口不會彈窗詢問
console.log("succ auth")
}, fail() {
console.log("fail auth")
}
})
} else {
console.log("record has been authed")
}
}, fail(res) {
console.log("fail")
console.log(res)
}
})
},
onHide: function () {
wx.stopBackgroundAudio()
},
** 正文使用 **
1, 獲取應用實例
const app = getApp();
2, 引入插件
const plugin = requirePlugin(“WechatSI”);
3,獲取全局唯一的語音識別管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager()
data:{
// 文字題內容
content: '',
// 音頻臨時文件地址
audioTempFilePath: '',
}
onLoad: function (options) {
// 微信同步傳譯
that.initRecord();
// 授權語音
app.getRecordAuth();
},
/** 音頻開始錄製 */
startAudioRecording: function () {
let that = this;
manager.start(); // 語音識別開始
},
/** 音頻結束錄製 */
endAudioRecording: function () {
let that = this;
manager.stop(); // 語音識別結束
},
/**
* 初始化語音識別回調
*/
initRecord: function () {
let that = this;
//有新的識別內容返回,則會調用此事件
manager.onRecognize = (res) => {
that.setData({
content: res.result,
});
};
// 識別結束事件
manager.onStop = (res) => {
let text = res.result;
if (text == '') {
return $.failMsg("音頻識別失敗,請輸入內容");
}
that.setData({
audioTempFilePath: res.tempFilePath,
});
};
// 識別錯誤事件
manager.onError = (res) => {
$.hideLoading();
return $.failMsg("音頻識別失敗,請輸入內容");
};
},