Media Player start stop start

Viewed 24514

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

8 Answers

Hey please use following

for stop -> media player mp.seekTo(0); mp.pause();

again for start just call mp.start();

A simple solution is to Use pause instead of stop and the seek to the beginning of the song.

I know that this question is quite old but recently while learning Android, I also got stuck at this point and found a very simple solution which I'd like to share with everyone.

Instead of trying to stop or reset the media, you can just seek back to the starting position.

mediaPlayer.seekTo(0);

For reference, I am also posting my code below:

public class MainActivity extends AppCompatActivity {

    MediaPlayer mp;

    public void play(View view) {
        mp.start();
    }

    public void pause(View view) {
        mp.pause();
    }

    public void stop(View view) {
        // this seeks to the beginning of the file
        mp.seekTo(0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mp = MediaPlayer.create(this, R.raw.sample_audio);
    }
}
Related