Arenosa
Arenosa

Reputation: 41

How can I change sound volume with buttons in monogame?

I want to change the sound volume of my c# written monogame with buttons in the settings. I have two buttons. One for lower volume and one for higher volume. The functions behind the buttons are the following:

public static void VolumeHigher()
        {
            if (SoundEffect.MasterVolume != 1.0f)
            {
                SoundEffect.MasterVolume += 0.1f;
            }
        }

public static void VolumeLower()
        {
            if (SoundEffect.MasterVolume != 0.0f)
            {
                SoundEffect.MasterVolume -= 0.1f;
            }
        }         

There is a little change when I am clicking on higher or lower. When I am clicking on higher or lower a few times it is getting lower. It doesn't matter, if I click on higher or lower. It is getting lower. And it is only a little bit lower. You can hear it but i doesn't get quieter. At this moment there are only two volume steps. A "normal" one and a "little bit lower" one.

Another implementation:

public static void VolumeHigher()
        {


            if (SoundEffect.MasterVolume <= 1.0f || SoundEffect.MasterVolume >= 0.0f)
            {
                SoundEffect.MasterVolume += 0.1f;
            }
            else
            {
                Console.WriteLine("The sound is loud enough. Protect your ears!");
            }

        }

        public static void VolumeLower()
        {

            if (SoundEffect.MasterVolume > 0.0f || SoundEffect.MasterVolume <= 1.0f)
            {
                SoundEffect.MasterVolume += 0.1f;
            }
            else
            {
                Console.WriteLine("The sound is quiet. You don't hear it anymore!");
            }

        }

There I get the error System.ArgumentOutOfRangeException. I don't understand this exception, because 0.0f is silent, 1.0f is full volume. And in this code, the volume can't get out of the range.

How can I do it correctly? I din´t find help in the other questions here. Is there anybody who could help me, please?

Upvotes: 0

Views: 397

Answers (1)

abousquet
abousquet

Reputation: 586

The problem in your second code snippet is your usage of the || operator.

For example, in the VolumeHigher method, you are checking if the sound is smaller than 1.0f OR if the sound is greater than 0.0f. This will always be true in your case so you will add 0.1f and thus getting an ArgumentOutOfRangeException.

You can simply remove the "|| SoundEffect.MasterVolume >= 0.0f" and it should work fine.

Same logic applies for the VolumeLower method.

Upvotes: 1

Related Questions