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

Flutter iOS端使用audio_service与just_audio更新媒体项时长无效问题排查求助

Flutter iOS端使用audio_service与just_audio更新媒体项时长无效问题排查求助

各位好,我现在用Flutter开发iOS端的音乐播放器,用的是audio_service和just_audio这两个包,最近遇到了个头疼的问题——媒体项(MediaItem)的时长更新后,播放控制通知上就是不显示正确的时长,完全没达到预期效果。

先贴一下我的相关代码片段,麻烦大家帮我看看哪里出问题了:

首先是监听播放事件同步状态的部分:

_player.playbackEventStream.listen((PlaybackEvent event) {
  print("AS:_notifyAudioHandlerAboutPlaybackEvents: > ${event.currentIndex} > ${event.duration}");
  final playing = _player.playing;
  playbackState.add(playbackState.value.copyWith(
    controls: [
      MediaControl.skipToPrevious,
      if (playing) MediaControl.pause else MediaControl.play,
      MediaControl.stop,
      MediaControl.skipToNext,
    ],
    systemActions: const {
      MediaAction.seek,
    },
    androidCompactActionIndices: const [0, 1, 3],
    processingState: const {
      ProcessingState.idle: AudioProcessingState.idle,
      ProcessingState.loading: AudioProcessingState.loading,
      ProcessingState.buffering: AudioProcessingState.buffering,
      ProcessingState.ready: AudioProcessingState.ready,
      ProcessingState.completed: AudioProcessingState.completed,
    }[_player.processingState]!,
    repeatMode: const {
      LoopMode.off: AudioServiceRepeatMode.none,
      LoopMode.one: AudioServiceRepeatMode.one,
      LoopMode.all: AudioServiceRepeatMode.all,
    }[_player.loopMode]!,
    shuffleMode: (_player.shuffleModeEnabled) ? AudioServiceShuffleMode.all : AudioServiceShuffleMode.none,
    playing: playing,
    updatePosition: _player.position,
    bufferedPosition: _player.bufferedPosition,
    speed: _player.speed,
    queueIndex: event.currentIndex,
  ));
});

然后是我用来监听时长变化、更新对应媒体项的代码:

_player.durationStream.listen((duration) {
  var index = _player.currentIndex;
  if (index != null && duration != null) {
    final newQueue = queue.value;
    final oldMediaItem = newQueue[index];
    final newMediaItem = oldMediaItem.copyWith(duration: duration);
    newQueue[index] = newMediaItem;
    mediaItem.add(newMediaItem);
    print("AS:_listenForDurationChanges: > $index > $duration > ${queue.value[index].duration}");
  }
});

现在的问题是,控制台打印里能看到duration和更新后的queue.value[index].duration都是正确的,但iOS的播放控制通知里,媒体时长就是不更新,还是原来的默认值或者空状态。我确认了durationStream的监听是正常触发的,就是通知端不生效。

有没有大佬能给我一些排查方向或者解决思路?比如是不是更新媒体项的方式不对,或者audio_service在iOS端的状态同步有什么特殊的坑?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 09:39:31