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 2 times in a row, it doest 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 assets needs to play on every click
2
Answers
To avoid multiple button presses triggering multiple sound loops, you can introduce a debounce mechanism that prevents rapid consecutive presses from triggering the sound repeatedly. Here’s an example of how you can implement it:
In the code above, a Debouncer class is introduced to debounce the button presses. It takes a delay duration as an argument. When the run method is called, it cancels any existing timer and sets a new timer with the specified delay. The callback function provided to run will be executed only after the delay has elapsed without any subsequent button presses.
In the _MyAudioPlayerState class, the Debouncer instance is created with a delay of 500 milliseconds. The handleButtonPress method is modified to use the debouncer’s run method, passing the playSound function as the callback.
Use the assets_audio_player package.
The code below will play a sound on every button click no matter how fast you spam it.
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
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