// pages/speechToText/index.js const $$ = require('../../utils/util'); const app = getApp(); Page({ /** * 页面的初始数据 */ recordMannager: wx.getRecorderManager(), data: { imgUrl: $$.url.img, key: '', value: '', showModal: false, //按住说话显示 }, // 录音结束触发 _endRecord(e) { this._transferText(e); }, touchStart(e) { let that = this; wx.getSetting({ success(res) { if (res.authSetting['scope.record'] === false) { $$.hideLoading(); $$.showModal({ content: '抱歉!此功能需授权麦克风录音功能', confirmText: '跳转授权', success: (res) => { if (res.confirm) { wx.openSetting({ success(res) { if (res.authSetting['scope.record']) { $$.showToast({ title: '授权成功' }); } else { $$.showToast({ title: '授权失败' }); } }, }); } }, }); return false; } that.setData({ showModal: true }); // 开始说话 const options = { duration: 60000, sampleRate: 16000, numberOfChannels: 1, encodeBitRate: 96000, format: 'pcm', }; that.recordMannager.start(options); that.recordMannager.onStart(() => console.log('开始录音')); that.recordMannager.onError((e) => { console.log('onError', e); $$.showToast({ title: '抱歉!录音时间过短,请重新录入' }); that.setData({ second: 60, showModal: false }); }); }, }); }, touchEnd() { let that = this; that.recordMannager.onStop((e) => that._endRecord(e)); that.recordMannager.stop(); that.setData({ showModal: false }) console.log('结束录音'); }, // 语音转文字 _transferText(e) { console.log('开始识别', e); $$.showLoading(); let speakUrl = e.tempFilePath; let that = this; wx.uploadFile({ url: `${$$.baseUrl}${$$.url.sys}/api/wechat/xfyun/speech`, filePath: speakUrl, name: 'fileNames', header: { Authorization: app.globalData.token }, complete(res) { $$.hideLoading(); if (res.errMsg === 'uploadFile:ok') { const { code, data, msg } = JSON.parse(res.data); if (code === '0' || code === 0) { that.setData({ value: that.data.value + data || '', number: (that.data.value + data || '').length, }); } else { $$.showToast({ icon: 'error', title: msg }); } } else { $$.showToast({ icon: 'error', title: '录音转写失败' }); } }, }); }, // 表单修改 handleChange(e) { let key = e.currentTarget.dataset.key, value = e.detail; this.setData({ value: value, [key]: value.length }); }, // 下一步 or 上一步 handleNext(e) { // 获取当前页面栈 var pages = getCurrentPages(); console.log('this.data.value', this.data.value); console.log('this.data.key', this.data.key); // 上一个页面 var prevPage = pages[pages.length - 2]; // 直接设置数据对象到上一页面的data中 prevPage.setData({ twoValue: this.data.value, twoKey: this.data.key, }); wx.navigateBack({ delta: 1, }) }, /** * 生命周期函数--监听页面加载 */ onLoad(options) { let { type, value } = options console.log('type', type); this.setData({ key: type, value, number: value?.length || 0, }) wx.getSetting({ success(res) { if (res.authSetting['scope.record'] === false) { $$.hideLoading(); $$.showModal({ content: '抱歉!此功能需授权麦克风录音功能', confirmText: '跳转授权', success: (res) => { if (res.confirm) { wx.openSetting({ success(res) { if (res.authSetting['scope.record']) { $$.showToast({ title: '授权成功' }); } else { $$.showToast({ title: '授权失败' }); } }, }); } }, }); } } }) }, })