能力依赖于RecorderManager,唯一的全局录音管理器。录音功能的要求和限制与当前页面的其他音频播放/录音功能互斥。status是否为录音状态表示结束/录音不需要,RecorderManager对象的素材可以回收/结束录音。录音中编码(结果代码直接看文末)构造一个简单的DOM结构首先实现小程序导入的录音功能iconRecordfrom'../../static/images/icon_record.png'importiconRecordingfrom'../../static/images/icon_recording.png'//...data(){recordImg:iconRecord,//录音按钮的图标rm:null,//RecordingManager},//...mounted(){if(this.rm===null){//如果录音管理器没有初始化,先初始化this。rm=uni.getRecorderManager()}//绑定回调方法this.rm.onStart((e)=>this.onStart(e))this.rm.onPause((e)=>this.onPause(e))this.rm.onResume((e)=>this.onResume(e))this.rm.onInterruptionBegin((e)=>this.onInterruptionBegin(e))this.rm.onInterruptionEnd((e)=>this.onInterruptionEnd(e))this.rm.onError((e)=>this.onError(e))},//...方法:{//...recordAction(){if(this.recordImg===iconRecord){//设置e格式转MP3,最长60S,采样率22050this.rm.start({duration:600000,format:'mp3',sampleRate:22050,})//绑定回调方法开始录音后停止录音this.rm.onStop((e)=>this.onStop(e))}elseif(this.recordImg===iconRecording){this.rm.stop()},},onStart(e){console.log('开始录音',this.question,this.subQuesIndex)this.recordImg=iconRecordingconsole.log(e)},onPause(e){console.log(e)afterAudioRecord()},onResume(e){console.log(e)},onStop(e){console.log(e)this.recordImg=iconRecord//录音完成后上传录音this.uploadMp3Action(e)},onInterruptionBegin(e){console.log(e)},onInterruptionEnd(e){console.log(e)},onError(e){console.log(e)},uploadMp3Action(e){//TODOuploadMp3},},同时只能有一条录音,与音频播放互斥添加两个属性audioPlaying,audioRecording//src/ApptoglobalData.vueexportdefault{globalData:{//确保只播放一个音频ing全局且录音和播放操作互斥audioPlaying:false,audioRecording:false,},//...},在Util中添加一个判断方法//src/lib/Util.js//录音结束后释放录音能力exportfunctionafterAudioRecord(){getApp().globalData.audioRecording=false}//结束音频播放然后释放音频播放能力record*/exportfunctionbeforeAudioRecordOrPlay(type){constaudioPlaying=getApp().globalData.audioPlayingconstaudioRecording=getApp().globalData.audioRecordingif(audioPlaying||audioRecording){uni.showToast({title:audioPlaying?'请暂停otheraudioplaybackfirst':'PleaseendfirstOtherRecording',icon:'none'})returnfalse}else{if(type==='play'){getApp().globalData.audioPlaying=true}elseif(type==='record'){getApp().globalData.audioRecording=true}else{thrownewError('typeError',type)}returntrue}}改造原来的recordAction方法import{beforeAudioRecordOrPlay,afterAudioRecord}from'../../lib/Utils';//...recordAction(){-如果(this.recordImg===iconRecord){+if(this.recordImg===iconRecord&&beforeAudioRecordOrPlay('record')){//设置格式为MP3,最长60S,采样率22050this.rm.start({duration:600000,format:'mp3',sampleRate:22050,})//绑定开始录制后停止录制的回调方法this.rm.onStop((e)=>this.onStop(e))}elseif(this.recordImg===iconRecording){this.rm.stop()+afterAudioRecord()},},为了避免我们的uploadMp3Action方法的多次录音小程序录音上传完成,我们使用uni-app的uni.uploadFile()方法上传录音文件uploadMp3Action(e){constfilePath=e.tempFilePathconstoption={url:'xxx',filePath,header,formData:{filePath},name:'audio',}uni.showLoading({title:'Recordinguploading...'})returnawaituni.uploadFile(option)uni.hideloading()}最后在页面卸载的时候回收RecorderManager对象beforeDestroy(){this.rm=null}完成收工~