我有一个奇怪的问题。我将 prepareAsync 方法与 一起使用MediaPlayer
,但我声明的侦听器从未被触发。我尝试.mp3
从互联网(广播电台)流式传输实时信息。我为侦听器使用了内联方法,但我也尝试实现接口但没有成功。这是我的代码的一部分:
在会员部分:
String url = "http://<my_url>.mp3";
MediaPlayer mediaPlayer = new MediaPlayer();
在活动中onCreate()
:
ToggleButton playButton = (ToggleButton) findViewById(R.id.playToggleButton);
playButton.setOnClickListener(this);
playButton.clearFocus();
playButton.setClickable(false);
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
ToggleButton playButton = (ToggleButton) findViewById(R.id.playToggleButton);
playButton.setClickable(true);
mp.start();
}
});
preparePlayer();
然后,preparePlayer()
方法如下:
private void preparePlayer() {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
Toast.makeText(
MyStreamActivity.this,
getResources().getString(R.string.erreurIllegalArgument),
Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IllegalStateException e) {
Toast.makeText(
MyStreamActivity.this,
getResources().getString(R.string.erreurIllegalState),
Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(
MyStreamActivity.this,
getResources().getString(R.string.erreurIO),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
并且(仅作记录),onDetroy()
我做清洁的地方:
private void releaseMediaPlayer() {
if (mediaPlayer != null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
}