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

使用flutter_sound开发录音功能时遇到的问题求助

解决方案

1. 修正依赖导入与版本

  • 移除过时的flauto依赖,在pubspec.yaml中添加正确的flutter_sound依赖:
    dependencies:
      flutter_sound: ^9.2.13 # 请使用pub.dev上的最新稳定版
    
  • 替换导入语句为官方当前有效包:
    import 'package:flutter_sound/flutter_sound.dart';
    

2. 适配新版本API(替代废弃方法)

flutter_sound 9.x+版本重构了核心API,原openAudioSession()、closeAudioSession()、dispose()已被移除,替换为以下方法:

  • 用openRecorder()替代原openAudioSession(),用于初始化录音器
  • 用closeRecorder()替代原closeAudioSession(),用于释放录音资源
  • 无需手动调用dispose(),closeRecorder()会自动完成资源清理

3. 正确实现自定义MySoundRecorder类

class MySoundRecorder {
  final FlutterSoundRecorder _recorder = FlutterSoundRecorder();
  bool _isInitialized = false;

  // 初始化录音器
  Future<void> init() async {
    await _recorder.openRecorder();
    _isInitialized = true;
    // 可选:配置录音参数,比如采样率、编码格式
    await _recorder.setSubscriptionDuration(const Duration(milliseconds: 100));
  }

  // 开始录音,传入保存路径
  Future<void> start(String savePath) async {
    if (!_isInitialized) await init();
    await _recorder.startRecorder(
      toFile: savePath,
      codec: Codec.aacADTS, // 根据需求选择编码格式
    );
  }

  // 停止录音,返回音频文件路径
  Future<String?> stop() async {
    if (!_isInitialized) return null;
    return await _recorder.stopRecorder();
  }

  // 释放录音资源
  Future<void> release() async {
    if (_isInitialized) {
      await _recorder.closeRecorder();
      _isInitialized = false;
    }
  }
}

4. 生命周期与权限注意事项

  • 在页面initState()中调用myRecorder.init()完成初始化
  • 在页面dispose()中调用myRecorder.release()释放资源
  • 务必配置录音权限:
    • Android:在AndroidManifest.xml中添加<uses-permission android:name="android.permission.RECORD_AUDIO"/>
    • iOS:在Info.plist中添加NSMicrophoneUsageDescription说明权限用途

内容的提问来源于stack exchange,提问作者Shahrear Al Sakib

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:24:52