Skip to content Skip to sidebar Skip to footer

Playing Sound On Right Or Left Speaker On Mouseover

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,

Solution 1:

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.localsimport *

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 = Truewhile running: # main loopfor event in pygame.event.get():
        if event.type == QUIT:
            running = Falseelif 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 playif sound_played:
        channel.set_volume(left, right)

    pygame.display.flip()

Post a Comment for "Playing Sound On Right Or Left Speaker On Mouseover"