Skip to content
Advertisement

How do I change the volume in realtime for my music player (pygame)

I am trying to change the volume of my music in realtime for my music player.

My code:

"""Volume Input"""
VolumeLevel = tkr.Scale(player,from_=0,to_=1, 
                        orient = tkr.HORIZONTAL, resolution = 0.1)
def change_vol(_=None):
    pygame.mixer.music.set_volume(vol.get())
    vol = Scale(
    sound_box,

    
)

And here are the action events:

def Play():
    pygame.mixer.music.load(playlist.get(tkr.ACTIVE))
    var.set(playlist.get(tkr.ACTIVE))
    pygame.mixer.music.play()
    pygame.mixer.music.set_volume(VolumeLevel.get())
    print(pygame.mixer.music.get_volume())
    print(VolumeLevel.get())  

But I don’t know how to change the volume while the music is playing, it only changes the volume after I restart the song.

I tried:

while pygame.mixer.music.get_busy() is True():
    pygame.mixer.music.set_volume(VolumeLevel.get())

But that didn’t work it just game me an error.

Advertisement

Answer

If you don’t use OOP(and I dont think you do based on what you provided), this should be the solution:

VolumeLevel = tkr.Scale(player,from_=0,to_=1, 
                        orient = tkr.HORIZONTAL, command=change_vol, resolution = 0.1)
def change_vol(vol, _=None):
    vol *= 100
    pygame.mixer.music.set_volume(vol)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement