java - 按主页或返回按钮时音乐不会停止
问题描述
我在 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();
}
}
}
当我按下主页按钮或返回按钮时,我希望音乐结束
解决方案
在您的活动类中添加以下覆盖方法:
@Override
public void onPause() {
super.onPause();
stopBackground();
}
因此,如果您的应用程序正在后台运行并且媒体正在运行,那么它将被停止。
推荐阅读
- google-bigquery - 基于组和时间戳的唯一值
- amazon-web-services - UnexpectedStatusException:培训作业 sagemaker-scikit-learnxxxx 失败。原因:AlgorithmError:框架错误
- azure-devops - 如何在 Azure devops wiki 中发布代码覆盖率和测试结果
- angular - 如何修复此错误类型错误:无法以角度读取未定义的属性(读取“长度”)
- azure - 在 Cosmos 中加入数组或非数组对象
- python - 如何在带有 Pycharm 的 WSL/WSL2 中使用 Cython?
- android - 这里Android SDK与华为的兼容性
- fetch - 当我通过请求正文发送令牌时,Slack 的 apps.connections.open 返回“invalid_auth”
- c++ - ISO C++ 委员会不接受任何当前 C++ 标准的侵入式指针和容器的理由是什么?
- python-3.x - 将 Pandas 数据框列中的句子列表拆分为单独的列