【问题标题】:Music doesn't stop when I press home or back button按主页或返回按钮时音乐不会停止
【发布时间】:2019-08-30 18:02:00
【问题描述】:

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

}

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

【问题讨论】:

  • stopBackground 是从哪里触发的?
  • 游戏在你死后启动
  • 当用户按下主页或返回时,这并不意味着游戏引擎死机。

标签: java android


【解决方案1】:

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

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

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

【讨论】:

  • 我还建议保存一个布尔标志,以指示它由于主页按或后按而暂停。在 onResume 另一个你应该重写的方法中,检查音乐是否需要自动恢复
  • 是的,我同意如果需求朝着这个方向发展,那么它可以在这里暂停,并可以在onResume() 方法中恢复。
【解决方案2】:

如果可以的话,我建议您使用ProcessLifecycleOwner 来确定您的应用程序何时被发送到后台,以执行您需要的所有清理工作。

这里有plenty of answers,详细说明了如何使用或实现它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多