2011-05-21 83 views
0

我想代碼爲歌曲應該只播放5秒鐘之後播放器應該停止播放歌曲。我以下面的方式使用AsyncTask,它不會在5秒後停止,並且我不知道在哪裏爲以下代碼中的播放器停止編碼。 task.execute編碼只是延遲了5秒纔開始活動。請幫幫我。 在以下播放器正在播放歌曲但不停止。 我的代碼:異步任務問題在android中

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    text=(TextView)findViewById(R.id.text);  
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { 
     @Override 
     protected Void doInBackground(Void... params) { 
      Log.e("bpm", "in run method"); 
      processor = new BPM2SampleProcessor(); 
      processor.setSampleSize(1024); 
      EnergyOutputAudioDevice output = new EnergyOutputAudioDevice(processor);  
      output.setAverageLength(1024); 
      try { 
       player = new Player(new FileInputStream("/sdcard/taxi.mp3"), output); 
       player.play(); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } catch (JavaLayerException e) { 
       e.printStackTrace(); 
      } 
      Log.e("bpm"," bpm is "+processor.getBPM());    
      return null; 
     }   
     protected void onProgressUpdate(Void... params) 
     { 
      text.setText("bpm is "+processor.getBPM()); 
     }    
    }; 
    try {   
     task.execute((Void)null).get(5, TimeUnit.SECONDS); 
     player.close(); 
    } catch(Exception e) { 
     e.printStackTrace(); 
    }  
} 

回答

0

在設置此任務後,您不應該關閉播放器。應在創建任務後5秒調用player.close()。這可以通過使用Handler對象在您的實現doInBackground()中發佈停止播放器的Runnable對象來完成。