Delay with Flutter Audioplayers

!

I’m having an issue with the audioplayers package when using it with the Flutter Framework. I’m calling the play() function multiple times a second, and after a certain amount of calls, the sound has a delay and then all the sounds play at once.

I tested the audioplayers example from GitHub on my iPhone and the same issue occurs when repeatedly clicking the button as fast as possible.

Is there a way to stop the previous sound before playing the next one, or is there another idea to deal with this issue?

This is my current implementation:

    AudioCache upgradeSound = new AudioCache();

    void playUpgradeSound() {
       _playUpgradeSound(upgradeSound);
    }

     void _playUpgradeSound(AudioCache ac) async{
        await ac.play('audio/upgr.mp3');
     }

Thank you for your help!

To stop the previous sound before playing the next one, you can use the stop() function from the audioplayers package before calling the play() function again. Here’s an updated implementation that should solve your issue:

    AudioCache upgradeSound = new AudioCache();
    AudioPlayer audioPlayer;

    void playUpgradeSound() {
        if (audioPlayer != null) {
            audioPlayer.stop();
        }
        _playUpgradeSound(upgradeSound);
    }

     void _playUpgradeSound(AudioCache ac) async{
        audioPlayer = await ac.play('audio/upgr.mp3');
     }

By checking if audioPlayer is not null, you can ensure that there is a sound playing before stopping it. The audioPlayer variable is also used to store the current sound being played, so you can stop it before playing the next one.