I have a requirement to play .mp3
sound files one after another, with no break or gap in between. While there is no issue in playing the sound files sequentially, there is a pause between them which is unacceptable given the requirements.
I have tried three solutions, one using the standard flutter audioplayer
, and two using the just_audio
package.
The code for each three is as follows:
// STANDARD AUDIO PLAYER
import 'package:audioplayers/audioplayers.dart';
...
AudioPlayer player = AudioPlayer();
...
void _playAudio(
{required List<String> files, required int currentIndex}) async {
String fileName =
'audio/${files[currentIndex].toLowerCase()}.mp3';
await player.play(AssetSource(fileName), mode: PlayerMode.lowLatency);
player.onPlayerComplete.listen((event) {
if (currentIndex + 1 >= files.length) {
return;
}
_playAudio(files: files, currentIndex: ++currentIndex);
});
}
// JUST_AUDIO
import 'package:just_audio/just_audio.dart';
...
AudioPlayer player = AudioPlayer();
...
void _playAudio(
{required List<String> files, required int currentIndex}) async {
await AudioPlayer.clearAssetCache();
for (final file in files) {
await player
.setAsset('assets/audio/${file.mp3');
await player.play();
await player.pause();
}
}
// JUST AUDIO GAPLESS
import 'package:just_audio/just_audio.dart';
...
AudioPlayer player = AudioPlayer();
...
void _playAudio(
{required List<String> files, required int currentIndex}) async {
final playlist = ConcatenatingAudioSource(
// Start loading next item just before reaching it
useLazyPreparation: false,
children: [],
);
for (final file in files) {
playlist.add(AudioSource.asset(
'assets/audio/${file}.mp3'));
}
await player.setAudioSource(playlist);
await player.play();
}
Each of the above play the sounds, but only with a gap in between of approximately a second.
Does anyone know why this is, or have another approach?
Thanks very much
Two options from my point of view:
1. Set all your assets before you play
the code is not 100% correct, but you get my point
void _playAudio(
{required List<String> files, required int currentIndex}) async {
await AudioPlayer.clearAssetCache(); // is this gonna work?
final List<AudioPlayer> players = []; // array of players - yes, multiple players in the memory
for (final file in files) {
final AudioPlayer player = AudioPlayer(); // create the instance of one
await player.setAsset('assets/audio/${file.mp3}'); // set asset for the one player
players.add(player); // add it to the array
}
for (final player in players) {
await player.play(); // play the all players
await player.pause();
// delete a cache somehow?
}
}
2. Use different isolates for loading the asset