2014-01-16 80 views
0

我有這樣的代碼:如何使Android MediaPlayer更快?

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Button btSobre = (Button)findViewById(R.id.btInfo);  
    btPlay = (Button)findViewById(R.id.btPlay); 

    playTask = new PlayAsyncTask(); 
    mediaPlayer = new MediaPlayer(); 

    btPlay.setOnClickListener(new OnClickListener() {   
     @Override 
     public void onClick(View v) { 
     //playTask.execute();  
      try { 
       mediaPlayer.setDataSource("http://************"); 
      } catch (Exception e) {     
       e.printStackTrace(); 
      } 
      try { 
       mediaPlayer.prepare(); 
      } catch (Exception e) {     
       e.printStackTrace(); 
      } 

      if(mediaPlayer.isPlaying()){ 
       mediaPlayer.stop(); 
       imagemPlay(); 
      } else { 
       mediaPlayer.start(); 
       imagemPlay(); 
      }    
     } 
    });  

} 

//Troca a imagem do botão play. 
private void imagemPlay() { 
    if(mediaPlayer.isPlaying()){ 
     btPlay.setBackgroundResource(android.R.drawable.ic_media_pause); 
    } else { 
     btPlay.setBackgroundResource(android.R.drawable.ic_media_play); 
    } 

} 

當我ckick的按鈕來播放,它需要一些時間來播放音樂。我該如何做得更快,或者向用戶提供一些反饋? 像裝載機或其他東西一樣。

回答

1

您每次點擊播放時都會準備。嘗試檢查它是否先播放,然後停止播放。如果它沒有玩,就休息一下。試試這個重構的代碼,看看它是否有點快:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Button btSobre = (Button)findViewById(R.id.btInfo);  
    btPlay = (Button)findViewById(R.id.btPlay); 

    playTask = new PlayAsyncTask(); 
    mediaPlayer = new MediaPlayer(); 

    btPlay.setOnClickListener(new OnClickListener() {   
     @Override 
     public void onClick(View v) 
     { 

      try 
      { 
       imagemPlay(); 

       if(mediaPlayer.isPlaying()) 
       { 
        mediaPlayer.stop(); 
        return; 
       } 

       mediaPlayer.setDataSource("http://************"); 
       mediaPlayer.prepare(); 
       mediaPlayer.start(); 
      } 
      catch (Exception e) 
      {     
       e.printStackTrace(); 
      } 
    });  

} 

//Troca a imagem do botão play. 
private void imagemPlay() { 
    if(mediaPlayer.isPlaying()){ 
     btPlay.setBackgroundResource(android.R.drawable.ic_media_pause); 
    } else { 
     btPlay.setBackgroundResource(android.R.drawable.ic_media_play); 
    } 

} 
+0

我也不確定是否需要setDataSource每次和準備。 –

+0

我會盡力的。 Thaks。 – Roland