2

I wanna ask is there any stream to listen when the song get ended to do some stuff at that point in just_audio flutter package or is there any method to do that ?

Afridi Kayal
  • 2,112
  • 1
  • 5
  • 15

2 Answers2

5

Looking at the documentation, AudioPlayer instances have a field called playerState or playerStateStream (If you want to listen for events). playerStateStream can be listened to using the stream which has a field called processingState. This field contains all the information you require (Here is the list). If the processing state is completed, then the player has finished playing.


Example:

_player.playerStateStream.listen((playerState) {
    if (playerState.processingState == ProcessingState.completed) {
        // Some Stuff
    }
});
Afridi Kayal
  • 2,112
  • 1
  • 5
  • 15
  • Thanks for the response but don't understand very well tested it but getting problems, Can you show an example ? –  Jul 09 '21 at 07:18
  • Please add some code of the widget in which you are trying to listen to the end event. – Afridi Kayal Jul 09 '21 at 07:37
  • ```_player.playerStateStream.listen((state) { if (state == ProcessingState.completed) { // Some Stuff } else { // Some Other Stuff } });``` In a function which get called on initializing state –  Jul 09 '21 at 10:32
  • Yes. Dont forget to dispose the stream subscription in void dispose – Afridi Kayal Jul 09 '21 at 12:26
  • I have already disposed the player but error it shows a red wavy line on the ```state == ProcessingState.completed``` –  Jul 09 '21 at 17:53
  • I did not notice the mistake in your comment. I have updated the answer. try it – Afridi Kayal Jul 10 '21 at 04:59
  • Ok I got my mistake in if statement I have wrote ```state``` except ```state.processingState``` Now working thanks bro –  Jul 10 '21 at 05:02
0

To enhance the Afridi's answer: one can subscribe to another stream, playbackEventStream, to get updates for individual audio sources in a playlist. This is an example how to update the song name:

player.playbackEventStream.listen((e) => updateCurrentSong());
...
void updateCurrentSong() {
  setState(() {
    final int index = player.currentIndex ?? 0;
    currentSong = "${player.audioSource?.sequence[index].tag}";
  });
}

Mitrakov Artem
  • 1,355
  • 2
  • 14
  • 22