Setting volume globally in pygame.Sound module

2019-09-01 05:15发布

问题:

I have been trying to set volume to all the sound playing using pygame. def on_press(self): file_name = self.filename

    pygame.mixer.pre_init(44100, 16, 2, 4096) 
    pygame.init()
    pygame.mixer.init(44100)
    channel=pygame.mixer.Sound(file_name)
    channel.play(0)

every time I press a button in the front end, A sound plays. I can play as many sounds I can. Now my question is how do I control volume of all the music? Here I should create object for each file and set its volume value. Code is below

           channel=pygame.mixer.Sound(file_name)
           channel.play(0)

How do I set the volume globally? All files that are playing should be affected with given volume? Thanks for any help!

回答1:

I believe you have to set each one individually with Sound.set_volume(value). You will have to store each Sound instance you create and then loop through them when you want the volume to change. If you want to set each one depending on the volume it was already, you can do something like:

def set_all_volume(sounds,mult):
    for sound in sounds:
        vol = sound.get_volume()
        sound.set_volume(min(vol*mult,1.0))


回答2:

I'm using a function for setting the volume globally. The function contains a sound.set.volume() line where you can set the volume for all sound objects created with that function.

# Audio
pygame.mixer.init()

# Sound
def create_sound04(name):
    fullname = "audio/sound/" + name     # path + name of the sound file
    sound = pygame.mixer.Sound(fullname)
    sound.set_volume(0.40)
    return sound

With that function I create my sound objects.

closedGate = create_sound04("closedGate.wav")
openGate = create_sound04("openGate.wav")

They are all set to the same volume and ready to be played.

You can also create a second function with a different volume and/or different path using a different function name.