How to avoid IllegalStateException with MediaPlayer - android

I have a stop button and a play button. When I click the play button, the audio plays fine and when I press stop, the audio stops. However, if I accidently hit the stop button twice in a row, an IllegalStateException gets thrown and force closes. How can I keep this force close from happening. Essentially what I want is that if someone accidently hits the stop button twice, the program does nothing. Here is the code:
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alphabet);
Button play = (Button) findViewById(R.id.button1);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp = MediaPlayer.create(getBaseContext(), R.raw.e_1100);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
});
Button stop = (Button) findViewById(R.id.button2);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.release();
}
else if (mp.isPlaying() == false) {
// What do I put here???
}
}
});
}
}

try this
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}

Related

onDestroy mediaplayer release

I want when I click on back button on the phone to close current activity and get back to menu and stop Media Player
But I get error: Unfortunately Weapons has stopped! upon clicking on back button
So how to fix that?
public class pushke extends Activity {
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.guns);
initControls();
final MediaPlayer mp=MediaPlayer.create(this, R.raw.uzi);
ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()){
mp.pause();
mp.seekTo(0);
}
else{
mp.start();
}
}
});
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar)findViewById(R.id.seekBar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{ }
#Override
public void onStartTrackingTouch(SeekBar arg0)
{ }
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mp.release();
}
}
Logcat:
1) I want when I click on back button on the phone to close current
activity and get back to menu and stop Media Player
1) What do you mean by menu? I mean application menu or device menu or notification bar etc.
2) But I get error: Unfortunately Weapons has stopped! upon clicking on
back button So how to fix that?
2)
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(mp!=null){
mp.stop();
mp.release();
mp = null;
}
}
EDIT:
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.guns);
initControls();
mp=MediaPlayer.create(this, R.raw.uzi);
ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()){
mp.pause();
mp.seekTo(0);
}
else{
mp.start();
}
}
});
}
In On destroy before releasing media player please stop the media player

Call Release and play multiple sound

with this code I want to stop all the sounds that are being executed, and play only the button clicked, but calling the release, the sound becomes null and you can not run the sound again. but if you do not call release give me problem anyway. how can I find a solution to this conundrum?
Code:
public MediaPlayer mediaPlayer = null;
public Boolean playing = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.b1);
b1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
if(mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(menu.this, R.raw.b1);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
playing=true;
};
});
}
});
Button b2 = (Button)findViewById(R.id.b2);
b2.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
if(mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(getBaseContext(),R.raw.b2);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
};
});
}
});
}});
I solved by this:
b1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.release();
}
mediaPlayer = MediaPlayer.create(menu.this, R.raw.b1);
mediaPlayer.start();
}});

Android button click to play music, click again to stop sound

I have a button, when I click it plays music, how to do it, when I click second time, to stop the music?
Button two = (Button)this.findViewById(R.id.button2);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.two);
two.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp2.start();
}
});
Ok, this one works:
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.n);
one.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
if (mp1.isPlaying()) {
mp2.pause();
}
else {
mp2.start();
}
;
}});
The one with Pause above it works, but If I want to stop the music, it does not work.
Following not working:
#Override
public void onClick(View v) {
if (mp1.isPlaying()) {
mp2.stop();
}
else {
mp2.start();
}
;
}});
I get error: start called in state 0
error (-38, 0)
According to http://developer.android.com/reference/android/media/MediaPlayer.html, I suppose you could do something like this:
Button two = (Button)this.findViewById(R.id.button2);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.two);
two.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// If the music is playing
if(mp2.isPlaying() == true)
// Pause the music player
mp2.pause();
// If it's not playing
else
// Resume the music player
mp2.start();
}
});
You can actually write just
if(mp2.isPlaying())
instead of
if(mp2.isPlaying() == true)
It's just for the sake of understanding what is going on.
You could have a boolean check to see if it is started (and set the boolean to false) and if so stop the music, if not start it (and set the boolean to true). Something like:
public void onClick(View v)
{
if(musicPlaying == false)
{
mp2.start();
musicPlaying = true;
}
else
{
mp2.stop();
musicPlaying = false;
}
}
if(mp2.isPlaying()) {
mp2.pause();
} else {
mp2.start();
}
This is what I used to start and stop the music, you must prepare the MediaPlayer for playback. Note: this will start the music from where it stopped.Mediaplayer prepare() methodIf you are streaming music you should use prepareAsync ()
musicButton = (Button) findViewById(R.id.btn_dj_player);
musicButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {//check if a song is already playing
mp.stop();
try {
mp.prepare();//get the mediaplayer reeady for playback
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
mp.start();
}
}
});
If you have only one sound and you want it to start or stop with only one button than this may help .
Button button_name = (Button)this.findViewById(R.id.Your_button_id_Here);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.YOur_audio_File_name_here);
button_name.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
if(mp.isPlaying())
{
mp.pause();
}
else
{
mp.start();
}
}
});
Have you tried using the seekTo() function?
Something like:
if (mp.isPlaying()) {
mp.stop();
mp.prepareAsync();
mp.seekTo(0);
} else {
mp.start();
}
}
I am just guessing here, but might be worth looking into. :-)
I accomplished this as follows:
I declared a boolean variable:
boolean isButtonClicked = false;
Then I set up an if else in a method like so:
initPlaySound()
{
if(isButtonClicked)
{
player.start();
} else{
player.stop();
}
Lastly I set up an onClick of the button within the method:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
isButtonClicked = !isButtonClicked;
initPlaySound();
}
});
Basically, when the button is first clicked the boolean is set to the opposite of its' current state (false to true) and the code within the if executes. Once the button is clicked again the boolean is set to the opposite again (true to false) and the sound stops.
I solved this problem in a manual way. If sound is playing, i wrapped sound into beginning(seekTo(0)), then paused the sound. If sound is already paused, only seekTo(0) is called.
public void onClick(View v) {
if(mp.isPlaying()){
mp.seekTo(0);
mp.pause();
}
else{
mp.seekTo(0);
}
} ;
Add a global variable boolean flag=false;
if(flag==false)
{
mp=MediaPlayer.create(this, R.raw.abc);
mp.start();
playbutton.setText("Pause");
flag=true;
}
else if(mp.isPlaying()&&flag==true)
{
mp.pause();
playbutton.setText("Play");
flag=false;
}
This code will work if you want to use the same button as PLAY/PAUSE in your app. Hope this helps. Add this code in the button onClick() function which you are using to play or pause.

How to add soundButton(on&off) on a activity in android apps?

I Have created a branch activity .Now i wanted to add two button on that branch activity.
When i click on 'sound on' button then my beep sound on start and when i clicked on 'sound off' then my beep sound off. and also they hide simultaneously.
Thank's
MY Code on Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sound_layout);
soundBttnOn =(Button) findViewById(R.id.soundBttnOn);
soundBttnOn.setOnClickListener(
new OnClickListener(){
#Override
public void onClick(View v) {
startMediaPlayer();
}
}
);
soundBttnoff =(Button) findViewById(R.id.soundBttnOff);
soundBttnoff.setOnClickListener(
new OnClickListener(){
#Override
public void onClick(View v) {
stopMediaPlayer();
}
}
);
}
private void startMediaPlayer() {
mediaPlayer = MediaPlayer.create(SoundLayout.this,R.raw.keybutton5);
mediaPlayer.start();
}
private void stopMediaPlayer() {
if( mediaPlayer != null ) {
MediaPlayer mp = null;
mp.stop();
mp.release();
}
}
It showing no problem but it is not working too..:P..I am not able to implement sound.
You can do simple google search to find tons of samples for adding button. However for playing sound file check out the MediaPlayer class.
Button startBtn, stopBtn;
//get the reference of Button
....
final MediaPlayer mp = new MediaPlayer();
startBtn.onClickListener() {
public void onClick(View v) {
try {
mp.setDataSource(path+"/"+audio.mp3);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
stopBtn.onClickListener() {
public void onClick(View v) {
if(mp.isPlaying()) {
mp.stop();
//hide buttons
stopBtn.setVisibiltiy(View.GONE);
startBtn.setVisibility(View.GONE);
}
}
};
PS: For only on and off, you don't need two buttons, you could do with one button.
EDIT:
For single button, just use the playing state of Media player for deciding about the action to take on button click.
singleBtn.onClickListener() {
public void onClick(View v) {
try {
if(mp.isPlaying()) mp.stop();
else {
mp.setDataSource(path+"/"+audio.mp3);
mp.prepare();
mp.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};

How to play and pause in only one button - Android

I have two buttons in my media player that streams a radio station, play and pause. I want to make it only one button that has two function. First click I want to play it and second click I want to pause it. And when I click it again I want to play it. I need help. Here is my code.
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
play.performClick();
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pause();
}
});
}
private void play() {
Uri myUri = Uri.parse("Shoutcast URL");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
Create just one Button and add something like a buttonstatus. Then you can check the status in your listener.
For example:
boolean isPlaying = false;
playPause = (Button) findViewById(R.id.play);
playPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (isPlaying) {
pause();
}else{
play();
}
isPlaying = !isPlaying;
}
});
Boolean b = false;
Button play = (Button) findViewById(R.id.play);
play..setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if(b == false)
{
//write play code here
b= true;
}
else
{
// enter pause code here
}
}
}
You can use Toggle button:
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (toggleButton.isChecked()) {
play();
} else {
pause();
}
}
});
You can also remove the green bar from toggle button.
Toggle button Mkyong example
Android dev tutorial
You don't need to declare any boolean variable to check player state. There is a method already available in mediaplayer class named - isPlaying().
Try my code sequence for playpause using single button.
public void playpause(){
if(!mp.isPlaying()){ // here mp is object of MediaPlayer class
mp.start();
//showNotification("Player State Plying");
}
else if(mp.isPlaying()){
mp.pause();
//showNotification("Player State Pause");
}
}

Categories

Resources