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

使用just_audio和record插件在Flutter中播放录制音频遇iOS问题求助

iOS本地录制M4A无法用just_audio播放的解决方案

编码格式兼容问题

iOS端record插件默认录制的M4A可能采用了just_audio不支持的编码变体,而Android录制或网络下载的是标准AAC-LC编码。

  • 解决:录制时明确指定标准AAC-LC编码:
    final recorder = Record();
    await recorder.start(
      path: '你的本地文件路径.m4a',
      encoder: AudioEncoder.aacLc,
      bitRate: 128000,
      samplingRate: 44100,
    );
    

本地路径处理问题

iOS对沙盒路径要求严格,just_audio可能无法解析record生成的非绝对路径。

  • 解决:用path_provider获取合法的沙盒目录,生成绝对路径用于录制和播放:
    import 'package:path_provider/path_provider.dart';
    
    final directory = await getApplicationDocumentsDirectory();
    final filePath = '${directory.path}/recording.m4a';
    // 录制用这个路径
    await recorder.start(path: filePath, ...);
    // 播放也直接用这个绝对路径
    final player = AudioPlayer();
    await player.setFilePath(filePath);
    

iOS配置缺失

just_audio在iOS上需要特定配置才能正常读取本地音频文件。

  • 解决:在Info.plist中添加必要配置:
    <!-- 麦克风权限(录音需要) -->
    <key>NSMicrophoneUsageDescription</key>
    <string>需要访问麦克风录制语音</string>
    <!-- 允许加载本地文件 -->
    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsLocalNetworking</key>
      <true/>
    </dict>
    
    配置后执行pod install,重启Xcode再运行项目。

文件写入未完成

iOS录制停止后,文件可能还在缓冲写入,此时播放会因文件不完整失败。

  • 解决:停止录制后等待文件写入完成再播放:
    await recorder.stop();
    final file = File(filePath);
    // 等待文件大小稳定
    while (await file.length() == 0) {
      await Future.delayed(Duration(milliseconds: 100));
    }
    // 再初始化播放
    final player = AudioPlayer();
    await player.setFilePath(filePath);
    await player.play();
    

兜底转码方案

如果以上方法都无效,用flutter_ffmpeg将录制的文件转码为标准格式:

import 'package:flutter_ffmpeg/flutter_ffmpeg.dart';

final ffmpeg = FlutterFFmpeg();
// 转码为标准AAC-LC编码的M4A
await ffmpeg.execute('-i $inputFilePath -c:a aac -b:a 128k $outputFilePath');
// 播放转码后的文件
await player.setFilePath(outputFilePath);

内容的提问来源于stack exchange,提问作者Ali Assi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:21:12