I've been using just_audio to play music in my app for a few years. Shuffle used to work, but while testing the latest version I realized it is no longer working! At first I though this due to the latest version 0.10.0
which introduced changes to playlist and player.AudioSources
, but have realized this was broken before that without me noticing!
This is my code, updated for the latest version:
final AudioPlayer musicPlayer = AudioPlayer();
// Define the playlist
final _playlist = <AudioSource>[
AudioSource.uri(
Uri.parse('asset:assets/music/song1.mp3'),
),
AudioSource.uri(
Uri.parse('asset:assets/music/song2.mp3'),
),
//there are dozen more
];
Future<void> initializeMusicPlayer() async {
try {
// Load the playlist
await musicPlayer.setAudioSources(
_playlist,
preload: false, //tried both options, no luck
shuffleOrder: DefaultShuffleOrder(random: Random()), //not sure what random option does, I tried without it, but no luck!
);
await musicPlayer.setVolume(0.9);
await musicPlayer.setLoopMode(LoopMode.all);
await musicPlayer.setShuffleModeEnabled(true); //not sure why are there so many shuffle related options, I tried different combos, no luck!
await musicPlayer.shuffle(); //do I need this as well?
} catch (ex, st) {
FirebaseCrashlytics.instance.recordError(
ex,
st,
reason: 'initializeMusicPlayer',
);
}
}
Future<void> playMusic() async {
try {
await musicPlayer.play();
} catch (ex, st) {
FirebaseCrashlytics.instance.recordError(ex, st, reason: 'playMusic');
}
}
Calling playMusic
method plays the first song every time! I ran it longer and the other songs play in order too, no shuffling at all
Am I doing something wrong or should I raise a bug?
Everything is up to date (flutter, pubs, vscode, android studio, windows, gradle, AGP, kotlin, java, even my smart watch!)
This workaround works for me. If someone comes up with a better solution, I will accept it instead.
Future<void> initializeMusicPlayer() async {
try {
//TODO workaround as shuffle isn't working!
_playlist.shuffle(Random());
// Load the playlist
await musicPlayer.setAudioSources(
_playlist,
preload: false,
);
await musicPlayer.setVolume(0.9);
await musicPlayer.setLoopMode(LoopMode.all);
} catch (ex, st) {
FirebaseCrashlytics.instance.recordError(
ex,
st,
reason: 'initializeMusicPlayer',
);
}