1

I need an AudioPlayer in Flutter that, even if one sound is currently playing, if I play another one, the previous one cancels and the new one goes.

This works if I do this: audioPlayer.setReleaseMode(ReleaseMode.stop);

The problem is, if I play the same asset sound twice in a row, it doesn't work; the previous one needs to end before the audioplayer plays the second one. I need this asset to sound every time I press a button, so if I spam buttons, the asset needs to play on every click.

1 Answers1

0

Use the assets_audio_player package.

The code below will play a sound on every button click no matter how fast you spam it.

ElevatedButton(
  onPressed: () {
    AssetsAudioPlayer.newPlayer().open(
      Audio('assets/sounds/pop_alert.mp3'),
      autoStart: true,
      showNotification: false, 
    );
  },
  child: const Text('Click Me!'),
),

Extra tip:

The trick to making button presses sound responsive is to remove as much "silence" as possible from the audio file. This requires a bit of audio editing. For example this is the waveform of the "pop_alert.mp3" file I used.

before trim enter image description here

We need to trim the audio clip to remove as much silence as possible so that the sound plays immediately when the button is pressed. You can use free online tools such as Free Audio Trimmer to achieve that.

after trim enter image description here

Eric Su
  • 725
  • 6
  • 14