start method
Starts playing the audio, returns a function that can stop the audio.
Implementation
Future<StopFunction> start({double volume = 1.0}) async {
return _lock.synchronized(() async {
if (availablePlayers.isEmpty) {
availablePlayers.add(await _createNewAudioPlayer());
}
final player = availablePlayers.removeAt(0);
currentPlayers[player.playerId] = player;
await player.setVolume(volume);
await player.resume();
late StreamSubscription<void> subscription;
Future<void> stop() {
return _lock.synchronized(() async {
final removedPlayer = currentPlayers.remove(player.playerId);
if (removedPlayer != null) {
subscription.cancel();
await removedPlayer.stop();
if (availablePlayers.length >= maxPlayers) {
await removedPlayer.release();
} else {
availablePlayers.add(removedPlayer);
}
}
});
}
subscription = player.onPlayerComplete.listen((_) => stop());
return stop;
});
}