Farrukh Sajjad
Farrukh Sajjad

Reputation: 353

Game music keeps on playing in background

I am currently working on a level-based mobile game.

The issue I am facing is that when I minimize the game, the music keeps on playing in the background. And the weird thing is that it only happens on a limited number of android devices.

Feel free to leave your suggestions on how to get a workaround this.

I am attaching my audio manager-script code below, but not sure we have an issue there.

public class AudioManager : MonoBehaviour
{
    public static AudioManager Instance;
    private SoundyManager soundyManager;
    private AudioSource backGroundSound;
    private void Start()
    {
        Instance = this;
        soundyManager = FindObjectOfType<SoundyManager>(true);
        backGroundSound = BackgroundAudioController.Instance.GetComponent<AudioSource>();
        if (!PlayerPrefs.HasKey(PlayerPrefsManager.SoundAudioPref))
        {
            PlayerPrefs.SetString(PlayerPrefsManager.SoundAudioPref, "ON");
        }
        if (!PlayerPrefs.HasKey(PlayerPrefsManager.BackgroundMusicPref))
        {
            PlayerPrefs.SetString(PlayerPrefsManager.BackgroundMusicPref, "ON");
        }
        
        if (PlayerPrefs.GetString(PlayerPrefsManager.SoundAudioPref) == "OFF")
        {
            // SoundyManager.MuteAllSounds();
            soundyManager.gameObject.SetActive(false);
        }
        
        if (PlayerPrefs.GetString(PlayerPrefsManager.BackgroundMusicPref) == "OFF")
        {
            // SoundyManager.MuteAllSounds();
            backGroundSound.Stop();
            // soundyManager.gameObject.SetActive(false);
        }
        
    }

    public void MuteAllSounds()
    {
        // SoundyManager.MuteAllSounds();
        soundyManager.gameObject.SetActive(false);
        PlayerPrefs.SetString(PlayerPrefsManager.SoundAudioPref, "OFF");
    }

    public void UnMuteAllSounds()
    {
        soundyManager.gameObject.SetActive(true);
        // SoundyManager.UnmuteAllSounds();
        // SoundyController.UnmuteAll();
        PlayerPrefs.SetString(PlayerPrefsManager.SoundAudioPref, "ON");
    }

    public void MuteBackgroundSound()
    {
        backGroundSound.Stop();
        PlayerPrefs.SetString(PlayerPrefsManager.BackgroundMusicPref, "OFF");
    }
    
    public void UnMuteBackgroundSound()
    {
        backGroundSound.Play();
        PlayerPrefs.SetString(PlayerPrefsManager.BackgroundMusicPref, "ON");
    }
}

Upvotes: 0

Views: 231

Answers (1)

JOYSON S T
JOYSON S T

Reputation: 306

The best way to solve this is to use Application.isFocused. Use this in one of the updates in your script, preferably in the LateUpdate()

if(!Application.isFocused)
{
audioSource.stop();
}

Upvotes: 1

Related Questions