Search code examples
pythonaudiopygamevolume

Pygame: set absolute sound volume using multiple channels


I need to set different volumes for the right and left ears for a sound at every iteration of a loop. And I represent sound for left and right ears by using two channels one, for each ear.

However, based on the documentation every time set_volume is called it sets volume at a percentage of the previous value.

 channel1.set_volume(0.0, 0.5) # sets at 0.5
 channel1.set_volume(0.0, 0.5) # sets at 0.5 * 0.5 = 0.25

I currently avoid this problem by calling channel.play at every iteration of the loop, which resets the volume to 1. However it also just restarts the sound file at every iteration. Is there a better way to do this?

# Current implementation
while True:
   chan1.play(sound)
   chan1.set_volume(volLeft, 0.0)

   chan2.play(sound)
   chan2.set_volume(0.0, volRight)

There is a similar question (Setting volume globally in pygame.Sound module). I tried manipulating the volume of two different sound variables but the volumes don't change on the right and left ear

If this is not possible in pygame, do you know of any other python sound libraries in which this is possible?

Thank you


Solution

  • I manipulated the volume by assigning a Sound object to each channel and setting the volume for that sound object

    # initialise variables
    sound = pygame.mixer.Sound(sound_path)
    sound_2 = pygame.mixer.Sound(sound_path)
    chan1 = pygame.mixer.Channel(0)
    chan2 = pygame.mixer.Channel(1)
    
    # set channel to max
    chan1.set_volume(1, 0)
    chan2.set_volume(0, 1)
    
    # set sound to initial value
    sound.set_volume(0)
    sound2.set_volume(0) 
    
    chan1.play(sound, 50, 0, 0)
    chan2.play(sound2, 50, 0, 0)
    
    while True:
    
       volLeft = getLeftVol()
       volRight = getRightVol()
    
       # change volume of sound every iteration
       sound.set_volume(volLeft)
       sound2.set_volume(volRight)
    
       if isDone:
          break