Search code examples
androidandroid-mediaplayerandroid-audiomanager

Android MediaPlayer - Play sound twice while not finished


I added click sound to my Android app, but when I click too fast on buttons, the sound is played only once (beacause the first play is not finished yet). I want the sound to be played at each click.

I would like to know what is the best way to implement the behaviour that I want ?

I put the instantiation of the MediaPlayer in the onCreate() method and play it in the onClick()

@Override
protected void onCreate(Bundle savedInstanceState) {
    [...]
    mpClic = MediaPlayer.create(getApplicationContext(),R.raw.clic);
}


vButtonLeft.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        [...]               
        mpClic.start();
     }
});
  • I tried to stop() / prepare() it before the play() but I get the same thing.
  • I tried to instanciate a new MediaPlayer at each play, it works but I guess it is not recommended (and by the way, with this method, the sound in my activity stop if I spam the button too many times very quickly)

Thank you in advance :)


Solution

  • I found a workaround, I reduced the lenght of my clic sound (from 0.50s to 0.17s) so it finishes to play earlier ; then I initiate 2 instances of it. If I need to play the sound and the first instance is already playing, I play the second.

    private MediaPlayer mpClic1;
    private MediaPlayer mpClic2; 
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        [...]
        mpClic1 = MediaPlayer.create(getApplicationContext(),R.raw.clic);
        mpClic2 = MediaPlayer.create(getApplicationContext(),R.raw.clic);
    }
    
    vButtonRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                [...]
                if(mpClic1.isPlaying())
                    mpClic2.start();
                else
                    mpClic1.start();
            }
        });
    

    It's a workaround so if someone knows how to achieve the desire effect of replaying a MediaPlayer that is already playing, please tell it and I will put it as correct answer. :) Thank you.