首页 > 解决方案 > 按主页或返回按钮时音乐不会停止

问题描述

我在 android 上做我的第一个游戏,它几乎完成了,但我的音乐有问题,当你开始游戏或死亡时,音乐开始和结束,但如果你按下主页按钮或返回按钮,它不会'永远不要停止

我曾尝试在这里寻找解决方案,但我的代码无法正常工作

这是 SoundBank 类,游戏开始时调用 playBackground,死亡时调用 stopBackground

public class SoundBank {

    Context context;
    MediaPlayer background, hit;
    int mute;
    GameOver gameOver = new GameOver();

    public SoundBank(Context context){
        this.context = context;
        hit = MediaPlayer.create(context,R.raw.sfx_hit);
        background = MediaPlayer.create(context,R.raw.background);
        mute = gameOver.getMute();
    }

    public void playHit(){
        if(mute != 1){
            hit.start();
        }
    }

    public void playBackground(){
        if(background != null){
            background.start();
            background.setLooping(true);
        }
    }

    public void stopBackground(){
        if(background != null){
            background.stop();
        }
    }

}

当我按下主页按钮或返回按钮时,我希望音乐结束

标签: javaandroid

解决方案


在您的活动类中添加以下覆盖方法:

@Override
public void onPause() {
    super.onPause();
    stopBackground();
}

因此,如果您的应用程序正在后台运行并且媒体正在运行,那么它将被停止。


推荐阅读