項目用wepy寫的以 wepy爲例
export default class extends wepy.app {
..............
//
在app.json文件中引入微信同聲傳譯插件
plugins: {
WechatSI: {
version: '0.2.2',
provider: 'wx069ba97219f66d99'
}
}
}
<view
id="maikefeng"
catchtouchstart="streamRecord"
catchtouchend="end"
class="iconfont icon-maikefeng"
>
</view>
import wepy from 'wepy';
const plugin = requirePlugin('WechatSI'); // 引入語音識別插件
// 獲取**全局唯一**的語音識別管理器**recordRecoManager**
const manager = plugin.getRecordRecognitionManager();
export default class speechtranslation extends wepy.component {
data = {
recording: false, // 正在錄音
recordStatus: 0, // 狀態: 0 - 錄音中 1- 翻譯中 2 - 翻譯完成/二次翻譯 暫無翻譯需求
pic: '/images/microphone.gif'
};
methods = {
// 長按開始錄音
streamRecord(e) {
manager.start();
this.recording = true
this.setData({
recordStatus: 0,
});
},
// 離開按鈕錄音結束
end() {
// 防止重複觸發stop函數
if (!this.recording || this.recordStatus != 0) {
console.warn('has finished!');
return;
}
this.recording = false
// 停止錄音
manager.stop();
}
};
onLoad() {
this.getRecordAuth();
// 綁定識別結束事件
manager.onStop = res => {
// 獲取語音文字
let text = res.result;
if (text == '') {
this.showRecordEmptyTip();
return;
}
console.log(text);
// 向父組件傳遞獲取到的文字信息
this.$emit('getText', text);
};
}
/**
* 識別內容爲空時的反饋
*/
showRecordEmptyTip() {
this.setData({
recording: false,
bottomButtonDisabled: false
});
wx.showToast({
title: '請說話',
duration: 2000,
icon: 'success',
image: '/images/no_voice.png',
success: function(res) {},
fail: function(res) {
console.log(res);
}
});
}
// 權限詢問
getRecordAuth() {
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);
}
});
}
}