Bad state: Cannot fire new event. Controller is already firing an event

105 views Asked by At

I am in the process of developing an application that streams audio from URLs retrieved from a backend service. The goal is for the application to play audio tracks seamlessly, one after the other, without user intervention.

Unfortunately, I have encountered a recurring error that is hindering this functionality. Whenever I attempt to set a new audio source with the following code:

await _audioPlayer.setAudioSource(AudioSource.uri(Uri.parse(audioUrl)));

I receive the error message: "Bad state: Cannot fire new event. Controller is already firing an event."

To manage audio playback progression, I am currently utilizing the playbackEventStream with a listener that looks for the completion of the current track to trigger the next one, as shown below:

audioPlayer.playbackEventStream.listen((event) {
  if (event.processingState == ProcessingState.completed) {
    handleNextItem();
  }
});

Despite this, the error persists. I am seeking advice on how to resolve this issue so that audio playback can proceed smoothly from one track to the next. Any guidance or suggestions you could offer would be greatly appreciated

1

There are 1 answers

0
Vladyslav Ulianytskyi On

You can't call _audioPlayer.setAudioSource(..) multiple times. You should do it once on player start. You could try this:

class AppAudioHandler extends BaseAudioHandler {
  AppAudioHandler();
      AudioPlayer? _player;
      late ConcatenatingAudioSource _playlist;

      Future<void> initPlayer() async {
        try {
          if (_player != null) {
            await _player?.dispose();
          }
          _player = AudioPlayer();
        } catch (e) {
          print(e);
        }
      }


  Future<void> loadEmptyPlaylist() async {
    await initPlayer();
    _playlist = ConcatenatingAudioSource(
      children: [],
      useLazyPreparation: false,
    );
    await _player?.setAudioSource(_playlist);
  }
...

Then after player initialization:

await _audioHandler.loadEmptyPlaylist()

when you want to add track url you just updating playlist(e.g. add some method updatePlaylist(..) to the AppAudioHandler):

await playlist.add(AudioSource.uri(Uri.parse(audioUrl)));
...

More info here: just_audio