2

I am trying to make small program in python, using PyQt5. The program will as have two buttons, and a label in the middle. When the mouse goes over the label, I want to call a def, in order to change the button's color and play a sound from specific speaker (left or right)

I tried pygame, following some posts, but nothing. The sound is playing in both channels.

import time
import pygame

pygame.mixer.init(44100, -16,2,2048)
channel1 = pygame.mixer.Channel(0) # argument must be int
channel2 = pygame.mixer.Channel(1)
print('OkkK')

soundObj = pygame.mixer.Sound('Aloe Blacc - Wake Me Up.wav')
channel2.play(soundObj)
soundObj.set_volume(0.2)

time.sleep(6) # wait and let the sound play for 6 second
soundObj.stop()

Is there a way to fix this and choose the left-right speaker?

Also, is there a way to call a def, On Mouse Over a label?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70

1 Answers1

0

When you use pygame in general, prefer calling pygame.init() to initialise all of the pygame modules instead of typing separately pygame. module .init(). It will save you time and lines of code.


Then, to play a sound file in pygame, I generaly use pygame.mixer.Sound to get the file, then I call the play() function of the sound object.

So the following imports a sound file, then plays and pans it according to the mouse X position

import pygame
from pygame.locals import *

pygame.init() # init all the modules

sound = pygame.sound.Sound('Aloe Blacc - Wake Me Up.wav')) # import the sound file

sound_played = False
# sound has not been played, so calling set_volume() will return an error

screen = pygame.display.set_mode((640, 480)) # make a screen

running = True
while running: # main loop
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
        elif event.type == MOUSEBUTTONDOWN: # play the sound file
            channel = sound.play()
            sound_played = True
            # start setting the volume now, from this moment where channel is defined

    # calculate the pan
    pan = pygame.mouse.get_pos()[0] / pygame.display.get_surface().get_size()[0]
    left = pan
    right = 1 - pan

    # pan the sound if the sound has been started to play
    if sound_played:
        channel.set_volume(left, right)

    pygame.display.flip()
D_00
  • 1,440
  • 2
  • 13
  • 32
  • channel.set_volume(left, right) NameError: name 'channel' is not defined Should I add: 'channel = pygame.mixer.Channel(0)' ??? – Katsaberis Stelios Feb 03 '21 at 15:19
  • Sorry, I edit my answer. I forgot to manage the fact that the program don't need to set the volume if the sound hasn't been played. – D_00 Feb 04 '21 at 16:21