2017-05-09 188 views
1

我可以停止音頻,但如果我檢查我的Android Studio調試窗口,我看到MediaPlayer在後臺工作!如何正確停止MediaPlayer?

我彈奏的聲音那樣:

try { 
myMediaPlayer1 = new MediaPlayer(); 
myMediaPlayer1.setAudioStreamType(AudioManager.STREAM_MUSIC); 
myMediaPlayer1.setDataSource("http://myweb.com/audios/1.mp3"); 
myMediaPlayer1.prepare(); 
myMediaPlayer1.start();  
} catch (Exception e) { 
// TODO: handle exception 
} 

我通過按鈕或OnDestry那樣的點擊停止MediaPlayer的:

@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    myMediaPlayer1.stop(); 
} 

我通過USB連接調試。停止聲音後我看到MediaPlay在後臺運行: Here is the Screenshot:

回答

0

您需要使用mediaPlayer.release()發佈媒體播放器。如果MediaPlayer未播放任何歌曲/音頻,則不應停止MediaPlayer。請參閱下面的代碼獲取更多幫助

private void releaseMediaPlayer() { 
    try { 
     if (mediaPlayer != null) { 
      if (mediaPlayer.isPlaying()) 
       mediaPlayer.stop(); 
      mediaPlayer.release(); 
      mediaPlayer = null; 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

感謝,它的工作原理: 'myMediaPlayer1.setOnCompletionListener(新MediaPlayer.OnCompletionListener(){ @覆蓋 公共無效onCompletion(MediaPlayer的myMediaPlayer1) { releaseMediaPlayer(); } });'' – Json

0

有一個問題:

我可以運行音頻只有一次!

所以我必須在每次點擊按鈕時創建新的MediaPlayer。它可以工作,但是當音頻播放結束時MediaPlayer不會停留在BG中!只有當我把這個方法;

myMediaPlayer1.setOnCompletionListener 

再次點擊梅索德象下面這樣:

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

    myMediaPlayer1 = new MediaPlayer(); 
    myMediaPlayer1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
     @Override 
     public void onCompletion(MediaPlayer myMediaPlayer1) { 
      releaseMediaPlayer(); 
     } 
     }); 
     } 
     public void Play_Audio(View view) { 
    try { 
     releaseMediaPlayer(); 
     myMediaPlayer1=null; 
     myMediaPlayer1 = new MediaPlayer(); 
     player.setDataSource("http://myweb.com/audios/1.mp3"); 
     myMediaPlayer1.setAudioStreamType(AudioManager.STREAM_MUSIC); 
     myMediaPlayer1.prepare(); 
     myMediaPlayer1.start(); 
    } catch (Exception e) { 
     // TODO: handle exception 
    } 


myMediaPlayer1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
    @Override 
    public void onCompletion(MediaPlayer myMediaPlayer1) { 
     releaseMediaPlayer(); 
    } 
    }); 

} 
    private void releaseMediaPlayer() { 
     try { 
      if (myMediaPlayer1 != null) { 
      if (myMediaPlayer1.isPlaying()) 
      myMediaPlayer1.stop(); 
      myMediaPlayer1.release(); 
      myMediaPlayer1= null; 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
    } 
    } 

我現在的問題是:

爲什麼OnComplet ...在OnCreate中,不能正常工作?

它會被銷燬,當我們使MediaPlayer爲空時,也許。所以我要創建梅索德.setOnCompet ...通過點擊每次