2011-05-21 86 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对象来完成。