Search code examples
androidperformanceaudiobuttonplayback

Play sound on fast clicks android


I want to play a sound everytime that a button is pressed.

The problem is that, If I press it fast, then sometimes the sound plays.. But sometimes it does not play.

If I press a button 20 times, (very fast) then the sound should ideally play 20 times. But what happens is that the sound does not get time to complete. It plays 8-9 times on average.

I have initialised my mediaPlayer object. And this seems to work.

mp1.start();

I tried the following code too, But this plays the sound only the first time. After that the sound is never played.

if(mp1.isPlaying())
    mp1.stop();
    mp1.start();

Solution

  • The problem is, MediaPlayer class is comparatively a heavy weight object and might not be suitable to play small files in a smaller interval. So my suggestion for you is to use SoundPool.

    SoundPool is comparatively a less weight object and will help in your case.

    Here is a sample based on it,

    http://www.vogella.com/articles/AndroidMedia/article.html#tutorial_soundpool