Mediaplayer stops in android after 30 clicks

139 Views Asked by At

I've seen other posts on this but I cant figure out problem.

So I'm designing a calculator and all the numbers have one onclick method and all the operators have different . I have a method playSound() where the code is:

public void playSound(){

         MediaPlayer mp= MediaPlayer.create(this, R.raw.btn);

        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        if(mp.isPlaying())
        {
            mp.stop();
            mp.reset();
        }
            mp.start();


    }

I've tried release to. Can anyone let me know the efficient way to write this. I call this method inside the onclick methods. But after around 30 clicks it stops. I've also tried to create MediaPlayer global but it still stops. I've read mediaplayer is actually costly so we can use soundpool. But even soundpool is deprecated. Any help?

2

There are 2 best solutions below

6
On BEST ANSWER

Implement onComplition() Listener , and in that listener you can call release method

You created multiple instances of mediaplayer and not release mediaplayer instanace thats why issue is came After you release called your issue will be resolved

0
On

Initialize the MediaPlayer as a class attribute:

MediaPlayer media = MediaPlayer.create(this,R.raw. btn);

In the playSound() method:

public void playSound(){
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mp.reset();
        mp.start();
    }