Music playback not in random order using just_audio in Flutter

25 views Asked by At

I'm trying to implement random playback for my music list using the just_audio package in Flutter. However, the songs are not playing in a truly random order. I suspect there might be a missing step in my code.

Expected Result: I want the music player to play songs in the playlist randomly

StreamBuilder<bool>(
  stream: Provider.of<MusicPlayerController>(context, listen: fa 
  lse).player.shuffleModeEnabledStream,
 builder: (context, snapshot) {
   if (snapshot.hasError) {
      return Text('Error: ${snapshot.error}');
    }
  final shuffleModeEnabled = snapshot.data ?? false;
  return IconButton(
    icon: shuffleModeEnabled
      ? Icon(Icons.shuffle, color: Colors.orange, size: 5.h)
      : Icon(Icons.shuffle, color: Colors.white, size: 5.h),
    onPressed: () async {
    final musicPlayerController = Provider.of<MusicPlayerController>(context, listen: false);
    if (shuffleModeEnabled == false) {
      await musicPlayerController.shuffle();
    }
    await musicPlayerController.player.setShuffleModeEnabled(!shuffleModeEnabled);
  },
 );
},
),

Controller Class

class MusicPlayerController extends ChangeNotifier {

 final player = AudioPlayer();

  int  _playingIndex = -1;

 final GetMusicProvider _musicProvider;
 final PlayerStateles _playerStateles;

MusicPlayerController(this._musicProvider, this._playerStateles){
  player.playerStateStream.listen((state) {
   if (state.processingState == ProcessingState.completed) {
       playOrPause(_playingIndex+1,_musicProvider.musicList[_playingIndex+1].uri.toString());
     }
    });
   }

 Future<void> shuffle() async {
    await player.shuffle();
 }

Future<void> playOrPause(int index, String uri) async {

  if (index == _playingIndex) {
  
    if (player.playing){
      player.stop();
      icon(index);
   }
    else{ 
      player.play();
      icon(index);
   }
     notifyListeners();
  } else {
  
   player.setAudioSource(AudioSource.uri(Uri.parse(uri)));
   player.play();
  _playingIndex = index;
  _playerStateles.updateCurrentIndex(index);
  icon(index);
  _musicProvider.refreshPage();
  notifyListeners(); 
  
  }
}

Icon icon(int index) {
  if (index == _playingIndex) { 
    return player.playing ?  Icon(Icons.pause_circle) : 
  Icon(Icons.play_circle_outline_outlined) ;
  } else {
    return Icon(Icons.play_circle_outline_outlined);
  }
 }

}
0

There are 0 answers