Media Player start stop start

Slim C. picture Slim C. · Dec 13, 2013 · Viewed 22.5k times · Source

I am making a new android sound application. I made a clickable button to play sound when I click on it. But I also want it to stop playing sound when I click for the second time. That part works fine now here is the problem, when I click again on button to play sound again, it doesn't play it, Media player is completely stopped. I was looking on forums but I can't seem to find an answer that could help me. Here is my Activity:

  MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.prvi);

    final MediaPlayer mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
    final MediaPlayer mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);


    Button dugme = (Button) findViewById(R.id.dugme);
    dugme.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mpButtonClick1.isPlaying()) {
                mpButtonClick1.stop();
                mpButtonClick1.reset();

            }
            else {              
                mpButtonClick1.start();

            }


        }   

    });

When I try to write mpButtonClick1.prepare(); I get error Unhandled Exception Type IOE exception

Answer

gian1200 picture gian1200 · Dec 14, 2013

Try to use pause instead of stop.

Reason: if you pause the MediaPlayer, then you can resume it later. However, if you use stop, almost any other method won't work and you will have to prepare the MediaPlayer again (or create a new one).

enter image description here

More info: here and here

PS: don't forget to release the memory when you finish using the resources.