Flutter-如何知道 AudioService 已停止?

问题描述

我正在使用 audio_service 颤振包。如果音频服务停止,我想弹出一个播放器页面。如何获得音频服务停止事件?我没有找到任何事件来检查服务是否停止

解决方法

AudioService.running 将在服务运行时发出 true,在服务未运行时发出 false

要在 true 变为 false 时进行收听,您可以试试这个:

// Cast runningStream from dynamic to the correct type.
final runningStream =
    AudioService.runningStream as ValueStream<bool>;
// Listen to stream pairwise and observe when it becomes false
runningStream.pairwise().listen((pair) {
  final wasRunning = pair.first;
  final isRunning = pair.last;
  if (wasRunning && !isRunning) {
    // take action
  }
});

如果您想监听 stopped 的播放状态,则需要确保您的后台音频任务实际上在 onStop 中发出该状态更改:

  @override
  Future<void> onStop() async {
    await _player.dispose();
    // the "await" is important
    await AudioServiceBackground.setState(
        processingState: AudioProcessingState.stopped);
    // Shut down this task
    await super.onStop();
  }

这样,您就可以在 UI 中监听此状态:

AudioService.playbackStateStream.listen((state) {
  if (state.processingState == AudioProcessingState.stopped)) {
    // take action
  }
});