2011-01-09 54 views
14

我正在嘗試使用SeekBar來顯示MediaPlayer類所播放的軌道的長度,並啓用在軌道中搜索。Android SeekBar setProgress導致我的MediaPlayer跳過

尋求在軌道內運作良好。但是,在軌道播放時使用setProgress更新進度值似乎會導致略微跳過。

在onCreate方法中,我使用一個循環創建一個線程,該線程更新當前軌道的SeekBar的進度值。該循環在軌道改變時重置。

private void createProgressThread() { 

    _progressUpdater = new Runnable() { 
     @Override 
     public void run() { 
      //Exitting is set on destroy 
      while(!_exitting) { 
       _resetProgress = false; 
       if(_player.isPlaying()) { 
        try 
        { 
         int current = 0; 
         int total = _player.getDuration(); 
         progressBar.setMax(total); 
         progressBar.setIndeterminate(false); 

         while(_player!=null && current<total && !_resetProgress){ 
          try { 
           Thread.sleep(1000); //Update once per second 
           current = _player.getCurrentPosition(); 
           //Removing this line, the track plays normally. 
           progressBar.setProgress(current); 
          } catch (InterruptedException e) { 

          } catch (Exception e){ 

          }    
         } 
        } 
        catch(Exception e) 
        { 
         //Don't want this thread to intefere with the rest of the app. 
        } 
       } 
      } 
     } 
    }; 
    Thread thread = new Thread(_progressUpdater); 
    thread.start(); 
} 

理想情況下,我寧願不使用線程,因爲我知道這有缺點。也請原諒吞嚥異常 - 很難繼續檢查所有MediaPlayer狀態以響應UI事件。但是,我真正的問題是音樂正在跳過。

任何人都可以提出一種替代方法來更新進度,並解釋爲什麼setProgress的調用即使使用單獨的線程也會導致曲目跳過?

在此先感謝。

回答

23

我認爲問題在於,當您調用setProgress()時,onProgressChanged事件被觸發。

監聽器(OnSeekBarChangeListener)有一個方法 public void onProgressChanged(SeekBar seekBar,int progress,boolean fromUser)。在這裏,您應該測試一下,如果偵聽器是由用戶操作或代碼觸發的。 在你的情況下,fromUser變量應該是false。

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 
    if(fromUser){ 
      player.seekTo(x); 
     } 
     else{ 
     // the event was fired from code and you shouldn't call player.seekTo() 
     } 
} 
+0

現貨上。謝謝。 – 2011-01-09 20:53:55

相關問題