当前位置: 首页 > Web前端 > HTML5

微信jsdk录音功能

时间:2023-04-05 22:08:39 HTML5

需求说明做一个H5页面,打开后可以录音,将录音文件提交到后台微信录音最大录音时长1min微信官方文档——音频接口代码如下//isVoice:0-未录音1-录音2-录音完成//点击录音/录音按钮显示点击录音

//isListen//0-未试听/试听结束1-正在试听2-暂停试听//录音按钮显示重新录制

提交

||

?

data(){return{id:'',startTime:0,recordTimer:null,localId:'',//录音本地idserverId:'',//录音微信服务idshowMask:false,tip:1,//提交0-重新录音isVoice:0,//0-不录音1-录音2-录音完成audioisListen:0,//0-不听/听结束1-听2-暂停听data1:0,work:{},isPlay:false,//是否播放isSubmit:false,//是否已经提交}}//微信配置getConfig(){let_url=encodeURIComponent(window.location.href)//后台提供接口,传入当前url(返回基本配置信息)voiceApi.wechatConfig(_url).then(res=>{if(res.data.code==200){wx.config({debug:false,appId:res.data.content.appid,timestamp:res.data.content.timestamp,//必填,时间签名生成的时间StampnonceStr:res.data.content.nonceStr,//生成随机签名串所必需的signature:res.data.content.signature,//Required,signed//需要授权的API接口jsApiList:['startRecord','stopRecord','onVoiceRecordEnd','uploadVoice','downloadVoice','playVoice','pauseVoice','onVoicePlayEnd']})wx.ready(()=>{wx.onVoiceRecordEnd({//录音时间超过了complete没有停止一分钟就会执行回调complete:function(res){_this.isVoice=2_this.localId=res.localId;}})})}})},//开始录音){let_this=thisevent.preventDefault()//延迟后记录以避免误用this.recordTimer=setTimeout(function(){wx.startRecord({success:function(){_this.startTime=newDate().getTime()_this.isVoice=1},取消:function(){_this.isVoice=0}})},300)},//停止录音voiceEnd(event){this.isVoice=2let_this=thisevent.preventDefault()//间隔太短if(newDate().getTime()-this.startTime<300){this.startTime=0//没有记录clearTimeout(this.recordTimer)}else{wx.stopRecord({success:function(res){//localId生成的WeChat,此时语音还没有上传到微信服务器_this.localId=res.localId},fail:function(res){console.log(JSON.stringify(res))}})}},//tryListen(){let_this=thiswx.playVoice({localId:_this.localId//待播放音频的本地ID,从stopRecord接口获取})console.log('试听..')wx.onVoicePlayEnd({//监听结束播放成功:function(res){console.log('监听监听结束')_this.isListen=0}});},//停止监听tryStop(){let_this=thiswx.pauseVoice({localId:_this.localId//待停止音频的本地ID,从stopRecord接口获取})},//处理录音数据voiceHandle(){let_this=thiswx.uploadVoice({localId:this.localId,//待上传音频的本地ID,从stopRecord接口获取isShowProgressTips:1,//默认为1,并且显示进度提示success:function(res){//微信语音已上传到微信服务器并返回一个Serverid_this.serverId=res.serverId;//返回音频的服务器端ID_this.upVoice()}})},//UpVoice(){letdata={id:this.id,serviceId:this.serverId}voiceApi.upVoice(data).then(res=>{if(res.data.code==200){//!!todo隐藏加载this.isSubmit=truethis.$Message.message('提交成功')this.closeMask()}else{this.$Message.message(res.data.message)}}).catch(err=>{console.log(err)})},**1.微信jsdk配置****2.调用微信录音启动方法wx.startRecord****3。调用微信录音结束方法wx.stopRecord**并返回一个本地音频idlocalId??如果不调用录音结束方法,1分钟后录音自动结束,需要wx.onVoiceRecordEnd监听录音结束**4。上传录音到微信服务器wx.uploadVoice**返回serverId??微信存储时间有限,有效期3天??目前多媒体文件下载接口频率限制为10000次/天,如果需要增加频率,请登录微信公众平台,在开发-界面权限列表中,申请增加临时上限**5。调用自己的后台上传到自己的服务器**这个可以看成是把serverId传给自己的服务器,然后自己的服务器调整微信提供的接口下载(serverId)到自己的服务器存储