微信小程式語音轉文字外掛--------wepy小dome
阿新 • • 發佈:2018-12-02
專案用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); } }); } }