I'm working on a custom made tts engine, where I would like to have audio files be played one after another with short pause in between .
Here is my code that I Have issue with, when I press play all the sounds will play at once without a pause in between.
Im using:audioplayers.dart package
import 'package:audioplayers/audioplayers.dart';
void playSound() {
List<String> nameArray = sound.split('');
final player = AudioCache();
for (int curIndex = 0; curIndex < nameArray.length; curIndex++) {
Future.delayed(const Duration(milliseconds: 300), () {
player.play(nameArray[curIndex] + ".mp3"); // play next sound
developer.log('0', name: nameArray[curIndex]);
curIndex++;
});
}
}
Though this works perfectly with 300 millisecond pause in between every sound if I write it like this:
int curIndex = 0;
final player = AudioCache();
Future.delayed(const Duration(milliseconds: 300), () {
player.play(nameArray[curIndex] + ".mp3"); // play next sound
developer.log('0', name: nameArray[curIndex]);
curIndex++;
Future.delayed(const Duration(milliseconds: 300), () {
player.play(nameArray[curIndex] + ".mp3"); // play next sound
developer.log('0', name: nameArray[curIndex]);
curIndex++;
Future.delayed(const Duration(milliseconds: 300), () {
player.play(nameArray[curIndex] + ".mp3"); // play next sound
developer.log('0', name: nameArray[curIndex]);
curIndex++;
Future.delayed(const Duration(milliseconds: 300), () {
player.play(nameArray[curIndex] + ".mp3"); // play next sound
developer.log('0', name: nameArray[curIndex]);
curIndex++;
Future.delayed(const Duration(milliseconds: 300), () {
player.play(nameArray[curIndex] + ".mp3"); // play next sound
developer.log('0', name: nameArray[curIndex]);
curIndex++;
});
});
});
});
});
}
Though obviously this isn't solution... as I need this to be able to play hundred+ of times.
Would really appreciate if someone could help me figure out why first and second code have different outputs and how to have for loop do the same thing second indented code is doing.
Thank you
I've solved the issue in question, needed to add await and async to the method
void playSound() async {
List<String> nameArray = sound.split('');
final player = AudioCache();
for (int curIndex = 0; curIndex < nameArray.length; curIndex++) {
await Future.delayed(const Duration(milliseconds: 300));
player.play(nameArray[curIndex] + ".mp3"); // play next sound
developer.log('0', name: nameArray[curIndex]);
curIndex++;
}
}
Found this answer here on the site, wish I've checked it better though as well, the question was framed in computer science terms, so it would be hard to find it for me, and I'm learning that as well.