I have a strange problem. I use the prepareAsync method with the MediaPlayer
, but the listener that I declared just never gets fired. I try to stream a live .mp3
feed from the Internet (radio station). I use an inline method for the listener, but I also tried implementing the interface without any success. Here's a portion of my code :
In the member section :
String url = "http://<my_url>.mp3";
MediaPlayer mediaPlayer = new MediaPlayer();
In Activity 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();
Then, here's the preparePlayer()
method :
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();
}
}
And (just for the record), the onDetroy()
where I do the cleaning :
private void releaseMediaPlayer() {
if (mediaPlayer != null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…