I am making a simple app to play a online radio stream. I know how to set up the stream. Here is my code so far. It sets up the stream and plays it fine. But if I hit stop, I cannot get it to start again. Am I missing something obvious?
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // might take long! (for buffering, etc)
streamButton = (ToggleButton) findViewById(R.id.playstopstream);
streamButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, final boolean isChecked) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if(isChecked)
{
mediaPlayer.start();
}
else
{
mediaPlayer.stop();
mediaPlayer.reset();
}
}
public void playButton (View view){
if (isActive == false){
mediaPlayer.start();
isActive = true;
}else{
mediaPlayer.seekTo(0);
mediaPlayer.start();
}
}
Works OK with me.
Old question, but I came across it looking for this. Just use pause to stop, followed by seekTo(0) before restarting:
mediaPlayer.seekTo(0);
mediaPlayer.start();
Works without having to prepare the recorder again every time.
When you call mediaPlayer.reset()
mediaPlayer
goes to IDLE state.
For playback, you should do initialize to prepare before start.
You can check the mediaplayer state here: http://developer.android.com/reference/android/media/MediaPlayer.html.
Try this
@Override
public void onCheckedChanged(CompoundButton arg0, final boolean isChecked) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if(isChecked) {
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
}
else {
mediaPlayer.stop();
mediaPlayer.reset();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With