2010-11-30 157 views

回答

3

设置好MediaPlayer之后,我只需在onCreate()和onResume()方法中进行设置,检查MediaPlayer当前是否正在播放(MediaPlayerisPlaying()方法应该适合您),如果正在播放,请设置按钮的图像并单击处理程序将其更改为暂停按钮。如果MediaPlayer未播放,请将其设置为播放按钮。

您还需要处理事件的监听,例如MediaPlayer何时停止(完成播放音频文件),以及在按下按钮时颠倒按钮状态(即按下播放更改按钮暂停,反之亦然)。

2

我会用2个按键和隐藏其中的一个:

public class MyActivity extends Activity implements View.OnClickListener { 
    Button playBtn; 
    Button pauseBtn; 

    public void onCreate() { 
     playBtn = (Button) findViewById(R.id.playButton); 
     pauseBtn = (Button) findViewById(R.id.pauseButton); 
     playBtn.setOnClickListener(this); 
     pauseBtn.setOnClickListener(this); 
    } 

    public void onClick(View v) { 
     switch (v.getId()) { 
     case R.id.playButton: 
      // play music here 
      playBtn.setVisibility(Button.GONE); 
      pauseBtn.setVisibility(Button.VISIBLE); 
      break; 
     case R.id.pauseButton: 
      // pause music here 
      pauseBtn.setVisibility(Button.GONE); 
      playBtn.setVisibility(Button.VISIBLE); 
      break; 
     } 
    } 
} 
0
final Button bPlay = (Button)findViewById(R.id.bPlay); 
      MediaPlayer song1 = MediaPlayer.create(tutorialFour.this, R.raw.fluet); 
     Button bStop = (Button)findViewById(R.id.bStop); 
     bPlay.setWidth(10); 
     song1.setOnCompletionListener(new OnCompletionListener() { 

      public void onCompletion(MediaPlayer mp) { 

       bPlay.setText("Play"); 


      } 
     }); 
     bPlay.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       b=true; 

       if(bPlay.getText().equals("Play") && b==true) 
       { 

        song1.start(); 

        bPlay.setText("Pause"); 
        b=false; 
       } 

       else if(bPlay.getText().equals("Pause")) 
       { 
        x=song1.getCurrentPosition(); 
        song1.pause(); 
        bPlay.setText("Resume"); 
        Log.v("log",""+x); 
        b=false; 
       } 
       else if(bPlay.getText().equals("Resume") && b==true) 
       { 
        song1.seekTo(x); 
        song1.start(); 
        bPlay.setText("Pause"); 
        b=false; 
       } 


      } 

     }); 
2

,你可以使用一个的ImageButton并与切换布尔变量改变绘制的图像,在联合使用以检查状态按钮(播放/暂停)。 这是我是如何实现它

ImageButton playButton; 
private boolean playOn; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 

    // some code here 
    playButton = (ImageButton)findViewById(R.id.btn_play); 
    //other specifications and your code 
    } 

public void play(View view){ 
     myplayfunction(); 
} 

public void myplayfunction(){ 
    if (playOn){ 
     playOn=false; 
     playButton.setImageResource(R.drawable.icn_pause); 
    //your mediaplayer functions 
    }else{ 
     playOn=true; 
     playButton.setImageResource(R.drawable.icn_play); 
    //pause the mediaplayer 
    } 
} 

而且,不要忘了在最后切换您的ImageButton,onCompletionListener()的媒体播放器