简体   繁体   English

按下后退按钮时如何停止播放音频?

[英]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. 现在,当用户点击图像时,此代码可以很好地播放音频,但是,当我想退出此活动并转到其他活动时,即使我按下Home键,音频仍在播放中。 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. 在活动中创建一个onStop并将mp设为一个类变量,尽管我总是为此类内容创建/首选媒体播放器帮助程序类。 Then call mp.stop()/pause on onStop. 然后在onStop上调用mp.stop()/ pause。

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即可创建它:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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