微信小程序之权限验证及其授权

以录音功能为例记录一下微信小程序中授权的过程。

wxml:定义三个方法

<view>
  <button bindtap='record'>开始录音</button>
  <button bindtap='stop'>停止录音</button>
  <button bindtap='play'>播放录音</button>
  
</view>

js:

在文件顶部定义
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()

data: {
    tempFilePath:""
  },


record(){
    var that = this;
    wx.getSetting({
      success(res){
        if (res.authSetting['scope.record']){
          wx.showToast({
            title: '开始录音',
            icon: 'success',
            duration: 1000
          })
          that.start();

        } else {
          wx.authorize({
            scope: 'scope.record',
            success: function(){
              that.start()
            },
            fail:function(){
              wx.showModal({
                title: '提示',
                content: '无法使用录音功能',
                confirmText:"是"
              })
            }
          })
        }
      },
      fail:function(){

      }
    })
  },

start(){
    const options = {
      duration: 10000,//指定录音的时长,单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式,有效值 aac/mp3
      frameSize: 50,//指定帧大小,单位 KB
    }
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
  },
  stop(){
    recorderManager.stop();
    recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      console.log('停止录音', res.tempFilePath)
      const { tempFilePath } = res
    })
  },

play(){
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值