一、背景
微信小程序开发,内嵌h5页面,不能调用微信内部的插件
二、实现方式
通过安装 js-audio-recorder 插件实现既定需求
三、具体步骤
1、安装插件
npm i js-audio-recorder
2、引入
在需要使用的页面中引入:import Recorder from 'js-audio-recorder';
3、具体配置
1、定义recorderdata() {return {recorder: null};},2、页面加载时,初始化onLoad() {this.recorder = new Recorder();},3、具体方法methods:{4、鼠标点击方法startRecording() {this.recorder = new Recorder();Recorder.getPermission().then(() => {console.log('开始录音');this.titleShow = true;this.recorder.start(); // 开始录音},(error) => {uni.showToast({title: '请先允许该网页使用麦克风',icon:"error"});console.log(`${error.name} : ${error.message}`);});},5、鼠标松开的方法touchEnd() {this.yyShow = false;this.titleShow = false;const blob = this.recorder.getWAVBlob(); //调这个方法会自动调用stopconst newbolb = new Blob([blob], { type: 'audio/wav' });this.blobToBase64(newbolb).then((base64) => {7、调用后端接口this.$UniRequest.Post({url: this.$AppConfig.audio2text,para: {audioBase64: base64},success: (res) => {if (res.audiocont == 'null') {uni.showToast({title: '未识别到您的语音,请重试',icon: 'error'});this.customerText = '';} else {this.customerText = res.audiocont;}},fail: (err) => {uni.showModal({title: '提示',content: err,showCancel: false});}});}).catch((err) => {console.error(err);});},6、音频转base64blobToBase64(blob) {return new Promise((resolve, reject) => {const reader = new FileReader();reader.readAsDataURL(blob);reader.onload = () => {const base64 = reader.result.split(',')[1];resolve(base64);};reader.onerror = () => {reject(new Error('blobToBase64 error'));};});}}