2015-11-05 70 views
0

在我的應用程序中,用戶選擇計數如1,21,51,101,108,就像他使用按鈕或單選按鈕選擇時一樣,媒體播放器具有在多少次重複。如果他選擇21,媒體播放器應該重複播放音樂21次。在我的代碼中,如果我在for循環中使用while循環來阻塞UI,不允許停止或暫停播放,如果我沒有使用while循環,它只播放一次。我需要解決它,任何一個將不勝感激提前。下面我張貼我的整個代碼使用安卓媒體播放器重複播放音樂某些x時間

public class MainActivity extends Activity implements OnClickListener{ 
    private MediaPlayer mp; 
    int count; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     setVolumeControlStream(AudioManager.STREAM_MUSIC); 
     findViewById(R.id.button_1).setOnClickListener(this); 
     findViewById(R.id.button_2).setOnClickListener(this); 
     findViewById(R.id.button_3).setOnClickListener(this); 
     findViewById(R.id.button_4).setOnClickListener(this); 
     findViewById(R.id.button_5).setOnClickListener(this); 
     findViewById(R.id.pause).setOnClickListener(this); 
     findViewById(R.id.stop).setOnClickListener(this); 

    } 

    public void onClick(View v) { 

     switch (v.getId()) { 
     case R.id.button_1: 
      if (mp!=null) { 
       mp.release(); 
      } 

      player(3); 

      break; 
     case R.id.button_2: 
      if (mp!=null) { 
       mp.release(); 
      } 
      player(21); 

      break; 
     case R.id.button_3: 
      if (mp!=null) { 
       mp.release(); 
      } 
      player(51); 

      break; 
     case R.id.button_4: 
      if (mp!=null) { 
       mp.release(); 
      } 
      player(108); 

      break; 
     case R.id.button_5: 
      if (mp!=null) { 
       mp.release(); 
      } 

      break; 
     case R.id.pause: 

       mp.pause(); 


      break; 
     case R.id.stop: 

       mp.stop(); 


      break; 

     } 


    } 

    private void player(int count) { 
     // TODO Auto-generated method stub 
     mp = MediaPlayer.create(this, R.raw.a); 

     for (int i=1; i<=count ; i++){ 
      mp.start(); 
      while(mp.isPlaying()); 
    } 
     // mp.release(); 





} 
    @Override 
    protected void onDestroy() { 
     if(null!=mp){ 
      mp.release(); 
     } 
     super.onDestroy(); 
    } 

} 

回答

1

你可以通過設置yourCount整數實現這一點,有數字你要重複你的聲音,而不僅僅是這樣做

int count = 0; 
    mp.setOnCompletionListener(new OnCompletionListener() 

     @Override 
     public void onCompletion(MediaPlayer mp) { 
      if (count < yourCount) { 
       mp.start(); 
       count++; 
      } 
     } 
    }); 
    mp.start(); 
+0

我在哪裏想要t o在我的代碼中創建或切換條件中實現它。 –

+0

在您播放音樂的播放器方法中 –

+0

OnCompletionListener無法解析錯誤即將到來 –

3

試試這個,希望它可以幫助

mp.setOnCompletionListener(新OnCompletionListener(){

@Override 
    public void onCompletion(MediaPlayer mp) { 
     // TODO Auto-generated method stub 
     // Count here and restart if required. 
    }});