uniapp scope.record 的使用方法

在uniapp中使用scope.record时遇到问题,具体应该如何调用?需要配置哪些权限?能否提供一个完整的示例代码?

2 回复

在uni-app中,scope.record通常用于获取表单或列表中的当前行数据。例如,在<picker>或列表渲染中,通过@change事件传递scope参数,使用scope.record访问当前项的数据对象。


在 UniApp 中,scope.record 通常与微信小程序的录音功能相关,用于获取用户授权并实现音频录制。以下是基本使用方法:

1. 用户授权

首先需要获取用户授权,可以使用 uni.authorize

uni.authorize({
  scope: 'scope.record',
  success() {
    console.log('授权成功');
    // 开始录音操作
  },
  fail() {
    console.log('授权失败');
  }
});

2. 录音管理

使用 uni.getRecorderManager() 管理录音:

const recorderManager = uni.getRecorderManager();

// 开始录音
recorderManager.start({
  duration: 10000, // 录音时长(ms)
  sampleRate: 44100, // 采样率
  numberOfChannels: 1, // 声道数
  encodeBitRate: 192000, // 编码码率
  format: 'aac' // 音频格式
});

// 监听录音结束
recorderManager.onStop((res) => {
  console.log('录音文件:', res.tempFilePath);
  // 这里可以上传或播放录音文件
});

3. 注意事项

  • 平台差异scope.record 主要在微信小程序中有效,其他平台(如 H5)可能需要使用 Web API(如 navigator.mediaDevices.getUserMedia)。
  • 权限处理:如果用户拒绝授权,可引导用户手动开启(通过设置页)。
  • 生命周期:录音管理器需在页面卸载时及时停止和销毁。

4. 完整示例

<template>
  <view>
    <button @tap="startRecord">开始录音</button>
    <button @tap="stopRecord">停止录音</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      recorderManager: null
    };
  },
  mounted() {
    this.recorderManager = uni.getRecorderManager();
    this.recorderManager.onStop((res) => {
      uni.showToast({
        title: `录音完成: ${res.tempFilePath}`,
        icon: 'none'
      });
    });
  },
  methods: {
    startRecord() {
      uni.authorize({
        scope: 'scope.record',
        success: () => {
          this.recorderManager.start();
          uni.showToast({ title: '开始录音', icon: 'none' });
        },
        fail: () => {
          uni.showModal({
            title: '提示',
            content: '需要录音权限,请前往设置开启',
            showCancel: false
          });
        }
      });
    },
    stopRecord() {
      this.recorderManager.stop();
    }
  }
};
</script>

总结

通过 scope.record 授权结合 uni.getRecorderManager() 可实现完整的录音功能。注意处理用户授权状态和平台兼容性。

回到顶部