android中通過URL來播放背景音樂
阿新 • • 發佈:2018-12-11
private MediaPlayer mediaPlayer;
if(uri!=null) { Uri uri1 = Uri.parse(uri); try { mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(this, uri1); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { Log.e("MediaPlayer ","開始播放"); mp.start(); } }); } catch (Exception e) { e.printStackTrace(); } }
@Override protected void onDestroy() { super.onDestroy(); if (mediaPlayer != null && mediaPlayer.isPlaying()) { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } }
// 設定迴圈播放
// mediaPlayer.setLooping(true);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// 在播放完畢被回撥
play();
}
});