Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

android - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...