Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Media Player start stop start

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

like image 972
Slim C. Avatar asked Dec 13 '13 10:12

Slim C.


People also ask

How do I start MediaPlayer?

In some editions of Windows 10, it's included as an optional feature that you can enable. To do that, select the Start button, then select Settings > Apps > Apps & features > Manage optional features > Add a feature > Windows Media Player, and select Install.

How do I turn off MediaPlayer?

Calling stop() stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state.

What is MediaPlayer in Android?

MediaPlayer Class in Android is used to play media files. Those are Audio and Video files. It can also be used to play audio or video streams over the network.

How do I turn off MediaPlayer on Android?

1 Answer. Show activity on this post. MediaPlayer has an OnCompletionListener callback you can register to get notified when playback stops.


1 Answers

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.

like image 186
gian1200 Avatar answered Sep 27 '22 22:09

gian1200