media player play pause in android

淺唱寂寞╮ 提交于 2019-12-01 21:19:28

Change your button to say Play at first. Combine play and pause code into one. Set and check a flag to see if play or pause is pressed and change text accordingly.

So you'll only have one button and two boolean fields:

 boolean play=true, pause=false;      final Button playPause = (Button) findViewById(R.id.play);             playPause.setBackgroundResource(R.drawable.start);      playPause.setOnClickListener(mListener); 

Now, in your listener code, do this:

case R.id.play:              if(play)             {                 play=false;                 pause=true;                  //change image for button                 playPause.setBackgroundResource(R.drawable.start);                  try {                     mp.prepare();                 } catch (Exception e) {                     // TODO Auto-generated catch block                     e.printStackTrace();                 }                   mp.start();                 p.setVisibility(View.INVISIBLE);                 pu.setVisibility(View.VISIBLE);                 pu.setClickable(true);                 p.setClickable(false);                    //seekBar.setProgress(mp.getCurrentPosition());                    new Thread(myThread).start();                  }             if(pause)             {                 play=true;                 pause=false;                   //change image for button                 playPause.setBackgroundResource(R.drawable.pause);                  mp.pause();                 pu.setClickable(false);                 p.setVisibility(View.VISIBLE);                 pu.setVisibility(View.INVISIBLE);                 p.setClickable(true);             }             break; 

Change the text on your button accordingly.

You can use the following code:

if(!mp.isPlaying() || isCompleted) {   isCompleted = false;   mp.start(); } else {   mp.pause(); } 

add a variant:

private boolean isCompleted = true; 

add listener:

mp.setOnCompletionListener(new OnCompletionListener(){          @Override         public void onCompletion(MediaPlayer mp) {             // TODO Auto-generated method stub             isCompleted = true;         }}     ); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!