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

Flutter Just Audio无法播放完整播放列表,出现播放错误

问题分析与解决方案

你遇到的部分音频无法播放、报错FileNotFoundException的问题,结合代码和错误信息,核心原因在于播放列表构建的索引计算逻辑错误、未过滤空URI条目,还可能存在异步加载时机或权限遗漏的问题,以下是具体修复方案:

1. 重构播放列表构建逻辑,避免索引计算错误

你当前手动计算索引的方式极易出现越界或位置赋值错误,导致部分AudioSource未正确初始化。建议通过列表切片实现“从指定index开始播放”的需求,代码更简洁可靠:

@override
void initState() {
  super.initState();
  _buildAudioSource();
}

void _buildAudioSource() async {
  // 确保songModel已完成异步加载
  if (songModel == null || songModel!.isEmpty) return;

  // 过滤掉URI为空的无效歌曲
  final validSongs = songModel!.where((song) {
    final uri = song.uri;
    return uri != null && uri.isNotEmpty;
  }).toList();

  // 构建正确顺序的AudioSource列表
  List<AudioSource> audioSources = [];
  if (index >= 0 && index < validSongs.length) {
    // 将index之后的歌曲放在列表前端,之前的放在后端
    audioSources = [
      ...validSongs.sublist(index).map((song) => AudioSource.uri(Uri.parse(song.uri!))),
      ...validSongs.sublist(0, index).map((song) => AudioSource.uri(Uri.parse(song.uri!))),
    ];
  } else {
    // index无效时按原顺序构建列表
    audioSources = validSongs.map((song) => AudioSource.uri(Uri.parse(song.uri!))).toList();
  }

  // 设置播放源并添加错误处理
  await _audioPlayer.setAudioSource(
    ConcatenatingAudioSource(
      children: audioSources,
      // 单个音频播放失败时自动跳过,不中断整个播放列表
      handleError: (error, index) {
        print("跳过错误音频:$error,索引:$index");
        return true;
      },
    ),
  ).catchError((error) {
    print("播放源初始化错误:$error");
  });
}

2. 过滤无效URI,避免空路径报错

即使你确认大部分URI正确,仍可能存在媒体库中已删除但未更新的条目(uri为空),通过where过滤这些无效条目,可直接避免Uri.parse空字符串导致的FileNotFoundException。

3. 确认权限与异步加载时机

  • 权限检查:Android 13+需申请READ_MEDIA_AUDIO和POST_NOTIFICATIONS权限;iOS需在Info.plist中添加NSAppleMusicUsageDescription权限描述,确保权限已通过用户授权。
  • 异步加载时机:querySongs是异步方法,不要在initState中直接使用未加载完成的songModel,建议将播放源构建逻辑放在querySongs的then回调或FutureBuilder中,确保songModel已获取到完整数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:45:43