2

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?

Sagar
  • 416
  • 7
  • 23

2 Answers2

1

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

Yogesh Rathi
  • 6,331
  • 4
  • 51
  • 81
  • In my case when each button is pressed it calls this method. So technically in calculator the sounds keep playing with push of a button, So when should i release mediaplayer? – Sagar Aug 27 '16 at 19:40
  • It is possible to declare mediaPlayer variable global and creare obj only once ? – Yogesh Rathi Aug 27 '16 at 19:41
  • What i tried, was to define a mediaplayer mp globally and during oncreate i did following: mp=MediaPlayer.create(this,R.raw.btn); and doing this stops the sound after like 10 clicks – Sagar Aug 27 '16 at 19:50
  • 1
    Ok implement onCompletion listener and write code mp.release in oncompletion method, remove global variable – Yogesh Rathi Aug 27 '16 at 19:52
  • I check working perfectly, in your side issue is still coming – Yogesh Rathi Aug 27 '16 at 20:03
  • This Worked! Thank you Very much, I've accepted the answer. Cheers – Sagar Aug 27 '16 at 20:04
-1

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();
    }
Arlind Hajredinaj
  • 8,380
  • 3
  • 30
  • 45