You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Audio Recorder Player库onStopRecord函数录音停止异常求助

解决React Native Audio Recorder Player无法停止录音的问题

针对你遇到的onStopRecord函数无法正常停止录音的问题,可以从以下几个方向排查和修复:

1. 修正useCallback的依赖项

你的onStopRecord使用了useCallback但依赖数组为空,这会导致函数内引用的audioRecorderPlayer或setRecordSecs可能是组件初始渲染时的旧引用,无法正确操作当前实例。修改依赖数组:

const onStopRecord = React.useCallback(async () => {
  try {
    const result = await audioRecorderPlayer.stopRecorder();
    audioRecorderPlayer.removeRecordBackListener();
    setRecordSecs(0);
    console.log(result, "Recorder result");
  } catch (error) {
    console.error("Error stopping recorder:", error.message, error.stack);
  }
}, [audioRecorderPlayer, setRecordSecs]); // 加入必要依赖

2. 确保audioRecorderPlayer是单例实例

不要在组件内部重复创建实例,建议在组件外部初始化:

// 组件外部初始化单例
import AudioRecorderPlayer from "react-native-audio-recorder-player";
const audioRecorderPlayer = new AudioRecorderPlayer();

const YourComponent = () => {
  const [recordSecs, setRecordSecs] = React.useState(0);
  // 后续使用这个单例进行录音操作
};

3. 检查录音启动逻辑的正确性

确认startRecorder调用成功且正确添加了监听:

const onStartRecord = async () => {
  try {
    // 可自定义录音文件路径,不设置则使用默认路径
    const audioPath = `${RNFS.DocumentDirectoryPath}/recording.mp3`;
    await audioRecorderPlayer.startRecorder(audioPath);
    
    // 正确添加录音进度监听
    audioRecorderPlayer.addRecordBackListener((e) => {
      setRecordSecs(e.current_position);
    });
  } catch (startError) {
    console.error("启动录音失败:", startError);
  }
};

4. 验证权限与环境配置

  • Android: 确保AndroidManifest.xml中添加了必要权限:
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    并且在运行时动态申请权限。
  • iOS: 在Info.plist中添加麦克风权限描述:
    <key>NSMicrophoneUsageDescription</key>
    <string>需要访问麦克风进行录音</string>
    
    避免在iOS模拟器测试(部分模拟器不支持录音功能)。

5. 升级库版本

旧版本的react-native-audio-recorder-player可能存在停止录音的bug,执行以下命令更新到最新版:

npm install react-native-audio-recorder-player@latest
# 或使用yarn
yarn add react-native-audio-recorder-player@latest

内容的提问来源于stack exchange,提问作者rupal modi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:22:51