微信小程序:录音功能(授权、统计时长、上传)

最近呢,用小程序做了个录音的功能,接下来呢,与大家一起分享一下我的开发心得,希望能帮到大家。那我们就继续向下👇看吧~

需求呢,差不多是这样的:

  1. 单击开始录制(不是摁住不放哦)
  2. 点击完成上传录音
  3. 录音计时功能
  4. 当到达360s,自动进行上传

好了那来看看效果图吧,如下图所示:
录音.gif
接下来,进入主题,奥利给
一开始呢,打算用wx.startRecord(),后来看了下文档,发现从基础库 1.6.0 开始,本接口停止维护,被 wx.getRecorderManager 代替了,下面的我会说一下录音的几个重点功能,那我们继续向下走👇

1. data数据
data: {
    recorderManager: null,
    curTime: 0,
    recorder: {
      status: 'ready', // 'ready' | 'recording'
      text: '点击录制',
    },
    timer: null,
    secondes: 0,
    startTimestamp: 0,
    isupload: false
},
2.点击录制与停止
recordBtn: throttle(function () {
      let { status } = this.data.recorder;
      if(!this.data.isupload){
        if (status === 'ready') {
          this.getRecordLimit()
        } else if (status === 'recording') {
          this._endRecord()
        }
      }
 }, 1000),
3.开始录音
_startRecord() {
      this.data.startTimestamp = Date.now();
      const options = {
        duration: 600000,//指定录音的时长,单位 ms,最大为10分钟(600000),默认为1分钟(60000)
        sampleRate: 16000,//采样率
        numberOfChannels: 1,//录音通道数
        encodeBitRate: 96000,//编码码率
        format: 'mp3',//音频格式,有效值 aac/mp3
        frameSize: 50,//指定帧大小,单位 KB
      }
    
      //点击录制
      this.data.recorderManager.start(options);

      //开始录音计时
      this.countDown();

      this.data.recorderManager.onStart(() => {
        console.log('点击录制...')
      })

      //错误回调
      this.data.recorderManager.onError((res) => {
        console.log('录音失败', res);
      })
    },
4.停止录音
_endRecord() {
      clearInterval(this.data.timer);
      this.data.recorderManager.stop();
      this.data.recorderManager.onStop((res) => {
        console.log('停止录音', res)
        let filePath = res.tempFilePath;
        let duration = res.duration;
        if((Date.now() - this.data.startTimestamp) / 1000 < 2) {
          wx.showToast({
            title: '录音时间太短!',
            icon: 'none',
            duration: 1500
          }
          return;
        }
        this._uploadRecord(filePath, duration)
      })
 },
5.上传录音
export const ossUploadFile = (fileUrl) => {
    return new Promise((resolve, reject) => {
        //获取阿里云oss上传相关凭证
        getOssToken('audio/')
        .then(res => {
          let ossPolicy = res.data;
          let fileKey = getAudioFileKey();
          wx.uploadFile({
            url: '需要将录音上传到的域名' 
            filePath: fileUrl, // onStop之后生成的tempFilePath
            name: 'file', 
            formData: {
              'key': 'audio/' + fileKey,
              'policy': ossPolicy.policy,
              'OSSAccessKeyId': ossPolicy.accessId,
              'signature': ossPolicy.signature,
              "success_action_status": 200
            },
            success() {
                resolve(OSS_HOST + "/audio/" + fileKey)
            },
            fail(err) {
                reject('upload fail => ', err)
            }
          })
        })
        .catch(err => {
            reject('getOssTokenFail => ', err)
        })
    })
}
6.录音授权
getRecordLimit() {
      let that = this;
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.record']) { // 未授权
            wx.authorize({
              scope: 'scope.record',
              success () { // 一次才成功授权
                that._startRecord()
              },
              fail(err) {
                console.log(err)
                wx.showModal({
                  title: '温馨提示',
                  content: '您未授权录音,该功能将无法使用',
                  showCancel: true,
                  confirmText: "授权",
                  success: function (res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: (res) => {
                          if (!res.authSetting['scope.record']) {
                            //未设置录音授权
                            wx.showModal({
                              title: '提示',
                              content: '您未授权录音,功能将无法使用',
                              showCancel: false,
                              success: function () {}
                            })
                          } else { // 二次才成功授权
                            that._startRecord()
                          }
                        },
                        fail: function () {
                          console.log("授权设置录音失败");
                        }
                      })
                    }
                  },
                  fail: function (err) {
                    console.log("打开录音弹框失败 => ", err);
                  }
                })
              }
            })
          } else { // 已授权
            that._startRecord()
          }
        }
      })
    },
7.统计时长(包括自动停止录音,并上传录音)
countDown() {
   this.data.timer = setInterval(() => {
      this.data.secondes++;
      if (this.data.secondes > 360) {
          clearInterval(this.data.timer);
          this.data.recorderManager.stop();
          this.data.recorderManager.onStop((res) => {
              console.log('时辰已到,自动跳转')
              let filePath = res.tempFilePath;
              let duration = 360000;
              this._uploadRecord(filePath, duration)
           })
           return;
       }
       this.setData({
            curTime: this.data.secondes
       });
   }, 1000);
}
8.录音动画

这一块呢主要是运用帧动画写的,大家可以参考一下哦~

<view class="recode">
     <view class="record-wave-multiple">
         <view></view>
         <view></view>
         <view></view>
     </view>
     <view class="record-bgm"></view>
 </view>

.recode {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    color: #fff;
}
.recode .record-bgm {
    width: 105rpx;
    height: 105rpx;
    border-radius: 50%;
    background:rgba(105,129,255,1);
}
.recode .record-wave-multiple {
    position: absolute;
    left: 0; 
    top: 0;
}
.record-wave-multiple>view {
    display: inline-block;
    background-color: #6981FF;
    border: 0 solid #6981FF;
    position: absolute;
    top: -25rpx;
    left: -27rpx;
    width: 170rpx;
    height: 170rpx;
    border-radius: 100%;
    opacity: 0;
    -webkit-animation: circle-wave-multiple 1.8s cubic-bezier(.41,.4,.67,1) 0s infinite;
    animation: circle-wave-multiple 1.8s cubic-bezier(.41,.4,.67,1) 0s infinite;
}
.record-wave-multiple>view:nth-child(2) {
    -webkit-animation-delay: .6s;
    animation-delay: .6s;
}
.record-wave-multiple>view:nth-child(3) {
    -webkit-animation-delay: 1.2s;
    animation-delay: 1.2s;
}
@keyframes circle-wave-multiple {
    0% {
        opacity: 0;
        transform: scale(.4);
    }
    5% {
        opacity: .5;
    }
    100% {
        opacity: 0;
        transform: scale(1);
    }
} 

下面呢,给大家说一下几个注意事项:⚠️

  1. 在执行stop();的时候,记得在后面加上 onStop和onError,不然它会自动去找你有onStop或者有onError 的地方,如果需要共用的话不写也行,当然这是看情况的哦,一定切记!!!
  2. 在开发者工具上呢,会录不进去音,不过在真机上是没问题的

到此呢,咱的录音功能也就写的差不多了,如果说小编的代码有什么问题,或者需要优化的地方呢,或者需要帮助,欢迎在下方评论区留言,小编会第一时间出现在大家面前~

最后呢,祝大家每天开开心心,快快乐乐,让bug离地我们远远的,永远都不要出现,哈哈哈😁~

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值