我在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