微信小程序录音和播放录音

时间:2021-07-19 16:43:37
<view class='voiceTap' wx:if="{{status == 0}}">点击录音</view>
  <view class='voiceTap' wx:if="{{status != 0}}">
    <image src='/images/6006.png'></image>
  <view class='voicelong'>{{voicetime}}</view>
</view>
<view class='voiceNavi' bindtap='workaudio'>
  <view class='inner1'>
    <view class='inner2' wx:if="{{status == 0}}"></view>
    <view class='cube' wx:if="{{status == 1 || status == 3}}"></view>
    <view class='triangle' wx:if="{{status == 2}}"></view>
  </view>
</view>
 
page({
  data:{
     
    audio: 1,
    status: 0,
    voicetime: '0:00',
    src: '',
  
  },
  
  onLoad: function (options){
    var that = this;
    this.recorderManager = wx.getRecorderManager();
    this.recorderManager.onError(function () {
      // 录音失败的回调处理
      console.log(111)
    });
    this.recorderManager.onStop(function (res){
      that.setData({
        src: res.tempFilePath
      })
    }
 
  },
  
  // 点击开始/结束录音
  
   workaudio: function (event) {
        var that = this;
      var status = that.data.status;
      var sta, voicetime, interval, listen;
      if (status == 0) {//刚点击进入
        sta = 1;
        //开始录音
        this.recorderManager.start({
          duration: 60000,
          format: 'mp3' // 如果录制acc类型音频则改成aac
        });
        var runtime = 0;
        interval = setInterval(function () {
          runtime++;
          if (runtime < 10) {
            voicetime = '0:0' + runtime;
          } else {
            voicetime = '0:' + runtime;
          }
          if (runtime == 60) {
            clearInterval(interval);
            this.recorderManager.stop();
            that.setData({ status: 2 })
          }
          that.setData({ voicetime, interval, runtime })
        }, 1000)
      } else if (status == 1) {//录音结束
        sta = 2;
        this.recorderManager.stop();
        clearInterval(that.data.interval);
      } else if (status == 2) {//播放
        sta = 3;
        var long = (that.data.runtime) - 1
        listen = setInterval(function () {
          long--;
          console.log(long)
          if (long <= 0) {
            that.setData({ status: 2 });
            clearInterval(that.data.listen);
          }
           that.setData({ listen });
        }, 1000)
      that.playVoice();
      console.log(sta);
   } else if (status == 3) {
      sta = 2;
    that.innerAudioContext.pause()
   }
   that.setData({ status: sta })
  },
 
  
  // 播放录音
  playVoice: function (e) {
    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.onError((res) => {
      // 播放音频失败的回调
    })
    this.innerAudioContext.src = this.data.src; // 这里可以是录音的临时路径
    this.innerAudioContext.play()
  },
 
 
 
 
 
 
})