我在Unity中为Android制作了2D游戏,并且存在问题。 游戏中有声音(例如菜单按钮声音)可以很好地工作。在Unity中制作的Android游戏中的声音问题
当我离开游戏(例如使用主屏幕按钮)并返回时,声音也很好。
但是,如果我得到一个声音通知(电子邮件,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'代码发布解决方案。也许你的代码有问题。 – Programmer
我将我的代码添加到帖子中。谢谢。 – dtamas80
添加了我的答案。看一看。如果可能的话,避免使用“PlayOneShot”,只使用“播放”。我的代码示例应该能解决您的问题。 – Programmer