微信小程序如何实现录音功能

data数据

data:{
  playerState: 0, //0-录音  1-播放
  voice: "", //录音地址
  voiceType: false, //录音切换
  beginAndEnd: "请语音录入",
}
image.png
image.png
image.png
image.png

开始录音

tape() {
    if (this.data.playerState == 0) { //等于0,进行录音功能
      //正在录音点击后就结束录音,图标也该为播放图标,功能改为播放
      if (this.data.voiceType) { 
        //结束录音
        this.setData({
          voiceType: false,
          src: '/assets/imgs/player.png'
        })
        this.end() //调用结束录音的方法
      } else {
        //开始录音
        this.setData({
          src: '/assets/imgs/voiceEnd.png',
          beginAndEnd: "结束语音录入",
          voiceType: true
        })
        wx.showToast({
          title: '正在录音。。。',
          icon: 'none',
          duration: 60000
        })
        const options = {
          duration: 60000, //录音的时长
          sampleRate: 44100, //采样率
          numberOfChannels: 1, //录音通道数
          encodeBitRate: 192000, //编码码率,有效值见下表格
          format: 'wav', //音频格式
          frameSize: 50 //指定帧大小,单位 KB。传入 frameSize 后,每录制指定帧大小的内容后,会回调录制的文件内容,不指定则不会回调。暂仅支持 mp3 格式。
        }
        wx.getRecorderManager().start(options) //开始录音
        var num = 0
        this.data.interval = setInterval(() => { //限时录音60s
          num++
          if (num > 59) { //到60s调用停止录音方法
            this.end()
          }
        }, 1000)
      }
    } else { //不等0也就是1,进行播放
      if (this.data.voiceType) {
        this.setData({
          voiceType: false,
          src: '/assets/imgs/player.png',
          beginAndEnd: "播放录音"
        })
        innerAudioContext.stop() //停止。停止后的音频再播放会从头开始播放。
      } else {
        this.setData({
          voiceType: true,
          src: '/assets/imgs/stop.png',
          beginAndEnd: "停止播放"
        })
        //音频的数据链接,用于直接播放,仅支持绝对路径。
        innerAudioContext.src = this.data.voice 
        innerAudioContext.play() //播放
        innerAudioContext.onEnded(() => { //监听音频自然播放至结束的事件
          innerAudioContext.stop() //停止。
          this.setData({
            voiceType: false,
            src: '/assets/imgs/player.png',
            beginAndEnd: "播放录音"
          })
        })
      }
    }
  },

结束录音

//结束录音
  end() {
    clearInterval(this.data.interval) //清除定时器
    wx.hideToast() //隐藏正则录音的图标
    wx.showToast({
      title: '录音结束。。。',
      icon: 'none',
      duration: 2000
    })
    this.setData({
      beginAndEnd: "播放语音",
      playerState: 1,
      voiceType: false
    })
    var that = this
    //监听录音结束事件
    wx.getRecorderManager().onStop(res => { 
      console.log(res)
      //调用自定义事件,把音频上传并返回音频路径
      const {
        uploadRecord
      } = require('../../../http/picture.js')
      uploadRecord(res.tempFilePath).then(res => {
        console.log(res)
        that.setData({
          voice: JSON.parse(res).data,
          state: 1
        })
      })
    })
    wx.getRecorderManager().stop() //停止录音
  },
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。