YULIN

微信小程序实现录音并播放,解决IOS只能播放一次BUG

本代码已经过模拟器+安卓+ios真机测试

请输入图片描述
WXML代码

<button bindtap="start" class='btn'>开始录音</button>
<button bindtap="stop" class='btn'>停止录音</button>

--录音时长{{times}}-
<button bindtap="play" class='btn'>播放录音</button>
<button bindtap="stopPlay" class='btn'>暂停播放</button>

<view class="url">{{voidurl}}</view>

<view >录音、暂停录音,计时,播放录音,暂停播放录音 已通过开发工具+安卓+ios真机测试,录音结束后会显示音频地址,录音回放可以播放无数次</view>

JS代码

//在Page外定义变量:
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
var THandle = null

//计时代码
start_tims(){
let that = this
if (THandle != null) {
  clearInterval(THandle)
  THandle = null
  that.setData({
    times: 0
  })
}

THandle = setInterval(() => {
  that.setData({
    times:that.data.times+1
  })
}, 1000)
},
end_tims(){
let that  = this
clearInterval(THandle)
THandle = null
that.setData({
  times: 0
})
},

//开始录音的时候
start: function () {
let that  = this
const options = {
  duration: 10000,//指定录音的时长,单位 ms
  sampleRate: 16000,//采样率
  numberOfChannels: 1,//录音通道数
  encodeBitRate: 96000,//编码码率
  format: 'mp3',//音频格式,有效值 aac/mp3
  frameSize: 50,//指定帧大小,单位 KB
}
//开始录音
recorderManager.start(options);
recorderManager.onStart(() => {
  wx.showToast({
    icon:'none',
    title: '开始录音',
  })
  that.start_tims()
});
//错误回调
recorderManager.onError((res) => {
  console.log(res);
})

recorderManager.onStop((res) => {
  that.end_tims()
  this.tempFilePath = res.tempFilePath;
  this.setData({
    voidurl: res.tempFilePath
  })
  wx.showToast({ icon: 'none', title: '停止录音' })

  console.log('停止录音', res.tempFilePath)
  const { tempFilePath } = res
})
},
pause: function () {
recorderManager.pause();
recorderManager.onPause((res) => {
  wx.showToast({icon: 'none',title: '暂停录音'})
  console.log('暂停录音')

})
},
resume: function () {
recorderManager.resume();
recorderManager.onStart(() => {
  wx.showToast({ icon: 'none', title: '重新开始录音' })

  console.log('重新开始录音')
});
//错误回调
recorderManager.onError((res) => {
  console.log(res);
})
},
//停止录音
stop: function () {
wx.showLoading({
  title: '保存中',
})
console.log('停止录音')


recorderManager.stop();

},

//播放声音
play: function () {
innerAudioContext.src = encodeURI(this.tempFilePath)
// innerAudioContext.loop = true //循环播放
console.log('播放', innerAudioContext.src )
wx.showToast({ icon: 'none', title: '播放' })

innerAudioContext.play()

  innerAudioContext.onPlay((e) => {
    console.log('开始播放',e)
  })

innerAudioContext.onError((res) => {
  console.log(res.errMsg)
  console.log(res.errCode)
})
},

stopPlay(){
innerAudioContext.stop((e)=>{
  console.log('暂停播放',e)

})

}