how to stop music immediately on a button push?

I created an if statement that should stop the music from playing when clicking the mute button. However when i click the mute button to turn the music OFF it keeps playing until the audio clip has finished. - I was wondering if anyone else has ran into this problem? I dont want to kill all audio because i still want other sound clips such as collecting an item to play. I only want to kill the music immediately and not wait until the clip has ran through.

main menu controller code

 public void MusicButton()
    {
        //music not playing
        if(GamePreferences.GetMusicState() == 0)
        {
            GamePreferences.SetMusicState(1);
            MusicController.instance.PlayMusic(true);
            musicBtn.image.sprite = musicIcons[1];
            Debug.Log("play music is " + GamePreferences.GetMusicState() );
            
        } else if (GamePreferences.GetMusicState() == 1)
        {
            GamePreferences.SetMusicState(0);
            MusicController.instance.PlayMusic(false);
            musicBtn.image.sprite = musicIcons[0];
            Debug.Log("play music is " + GamePreferences.GetMusicState());
            

        }
    }

Music controller code (only showing the method instantiate in MainMenu)

public void PlayMusic(bool play)
    {
        if (play)
        {
            if (!audioSource.isPlaying)
            {
                audioSource.Play();
                Debug.Log("music is playing");
            }
            else
            {
                if (audioSource.isPlaying)
                {
                    audioSource.Stop();
                    Debug.Log("music is NOT playing");
                }
            }
        }
    }

Well if you want the clip to continue playing but you can’t hear it, you can just set the music audio source to volume to 0. This way the audio source will continue to play, but you just cant hear it.

You can also just turn the audio source on/off. This way the entire source is turned off but, when you turn it back on again, the clip will start from the beginning again.

I also have a music/sfx on/off stuff in my current game and all I check for is if the music button/sfx button gameobject is active, then play music/sound, else don’t play music/sound. :slight_smile: