Allrounder
Allrounder

Reputation: 695

How to stop audio from playing when back button is pressed?

Hi all here is my code:

   final ImageView imageView = (ImageView) findViewById(R.id.Image7);
   imageView.setImageResource(mFullSizeIds[position]);
   imageView.setOnClickListener(new View.OnClickListener() {

@Override
         public void onClick(View v) {
    MediaPlayer mp = MediaPlayer.create(Audio.this,mAudio[position]);  
    mp.start();

}

  });

Now this code works fine to play the audio when the user taps the image, however when I want to exit this activity and go to a different activity, the audio track is still playing, even when I press the home key the audio is still playing. How can I prevent this from happening? Is there a way to stop the track from playing when the user taps the image again or presses the back/home button?

Upvotes: 1

Views: 4351

Answers (3)

Ta-Zvi
Ta-Zvi

Reputation: 134

Override the onBackPressed method, and stop your MediaPlayer object, which is mp.

Upvotes: 1

Faisal
Faisal

Reputation: 2276

Create an onStop in the activity and make mp a class variable although I always create/prefer media player helper class for this sort of stuff. Then call mp.stop()/pause on onStop.

private MediaPlayer mp = null;

@Override
public void onStop() {
    super.onStop();

    if (mp != null) {
        mp.stop();
    }
}

then you just create it with removing the MediaPlayer before mp:

mp = MediaPlayer.create(Audio.this,mAudio[position]);

Upvotes: 1

Vrashabh Irde
Vrashabh Irde

Reputation: 14367

Add

   @Override
    public void onBackPressed ()
    {
      if (mp != null)
        mp.stop();
      super.onBackPressed();
    }

and

@Override
public void onPause ()
{
  if (mp != null)
  {
    mp.pause();
    mp.stop();
  }
  super.onPause();
}

Upvotes: 3

Related Questions