简体   繁体   中英

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?

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();
}

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]);

重写onBackPressed方法,并停止MediaPlayer对象mp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM