【发布时间】:2016-05-30 12:33:54
【问题描述】:
我在 Unity 中为 android 制作了 2d 游戏,但出现了问题。 游戏中的某些声音(例如菜单按钮声音)可以完美运行。
当我离开游戏(例如使用主页按钮)并返回时,声音也很好。
但如果我收到声音通知(电子邮件、skpye 等),游戏会静音,直到我退出并重新开始游戏。
我试图搜索解决方案并找到了 OnApplicationPause 方法,但它对我没有帮助。不知道为什么……
有人知道可能是什么问题或解决方案吗:)?
谢谢。
编辑
我将手机连接到电脑并尝试调试并遵循 OnApplicationPause 方法。
游戏开始时播放声音。
如果我按下主页按钮,audioSource.Pause();被调用,当我回到游戏时 audioSource.UnPause();也称为。还有声音。
如果我接到电话,audioSource.Pause();被调用,当我回到游戏时 audioSource.UnPause();也称为。但是没有声音。
如果我收到通知(例如电子邮件),则没有 audioSource.Pause() 语句并且声音消失了。
永远不会调用“if (audioSource == null)”和“if (!audioSource.isPlaying)”语句。
private AudioSource audioSource;
public AudioClip clip;
void Awake() {
if (audioSource == null) {
audioSource = gameObject.AddComponent<AudioSource>();
audioSource.loop = true;
audioSource.clip = clip;
}
if (!audioSource.isPlaying) {
audioSource.Play();
}
}
void OnApplicationPause(bool pauseStatus) {
//Check if this is Pause
if (pauseStatus)
{
//Pause Audio if it is playing
if (audioSource.isPlaying)
{
audioSource.Pause();
//Set to true so that we will detamine whether to Play() or UnPause() the music next time
audioSourcePaused = true;
Debug.Log("ifplaying->pause");
}
Debug.Log("pause");
}
//Check if this is Resume
if (!pauseStatus) {
//Make sure audio is not null. If null, getComponent again
if (audioSource == null) {
audioSource = gameObject.AddComponent<AudioSource>();
audioSource.loop = true;
audioSource.clip = clip;
Debug.Log("Null");
}
//Check if we paused the audio then resume
if (audioSourcePaused) {
audioSource.UnPause();
//Set to false so that we will detamine whether to Play() or UnPause() the music next time
audioSourcePaused = false;
Debug.Log("Unpause");
}
//Check if Audio is playing. Don't play if already playing.
if (!audioSource.isPlaying) {
audioSource.Play();
Debug.Log("play");
}
}
}
【问题讨论】:
-
OnApplicationPause是解决这个问题的正确方法。发布您的OnApplicationPause代码的解决方案。也许你的代码有问题。 -
我在帖子中添加了我的代码。谢谢。
-
添加了我的答案。看一看。如果可能,请避免使用
PlayOneShot,而只使用Play。我的代码示例应该可以解决您的问题。 -
@dtamas80 你解决了这个问题吗?
标签: c# android unity3d android-notifications android-audiomanager