Search code examples
flutterjust-audio

Flutter: With [just audio], is it possible to create a playlist that doesn't automatically jump to the next audio when the current finishes?


I'm using Flutter just audio and I'm creating a ContatenatingAudioSource like this:

// Define the playlist
final playlist = ConcatenatingAudioSource(
  // Start loading next item just before reaching it
  useLazyPreparation: true,
  // Customise the shuffle algorithm
  shuffleOrder: DefaultShuffleOrder(),
  // Specify the playlist items
  children: [
    AudioSource.uri(Uri.parse('https://example.com/track1.mp3')),
    AudioSource.uri(Uri.parse('https://example.com/track2.mp3')),
    AudioSource.uri(Uri.parse('https://example.com/track3.mp3')),
  ],
);

This works perfectly, but I can't seem to prevent the next audio from playing when the current one ends.

All I want is a playlist where I have to explicitly seek the next audio, whenever the current one ends.

Is it possible to do that?


Solution

  • It sounds like ConcatenatingAudioSource is not the right solution to your problem, because what it does is "concatenate" the audio of multiple items together so that they can be played continuously.

    If all you want is to have separate items that the user can switch between, then you can program it exactly that way:

    final items = [
      AudioSource.uri(Uri.parse('https://example.com/track1.mp3')),
      AudioSource.uri(Uri.parse('https://example.com/track2.mp3')),
      AudioSource.uri(Uri.parse('https://example.com/track3.mp3')),
    ];
    
    
    Future<void> selectItem(int index) {
      await player.setAudioSource(items[index]!);
    }
    

    Now, there is only ever one item in just_audio's playlist which means that when it completes, it completes. You can call selectItem(i) to switch to item i.

    This solution does mean that player.sequence will not contain a sequence of all items, it will only ever contain a single item. So if you were relying on that to render the list in your UI, you should instead use items (declared above).