2010-11-30 154 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()的媒體播放器