Playing sound on right or left Speaker on MouseOver [duplicate] - python

This question already has answers here:
How would I be able to pan a sound in pygame?
(3 answers)
Closed 1 year ago.
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?

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()

Related

Is there a way to select and move an image in pygame? [duplicate]

This question already has answers here:
How to draw a chessboard with Pygame and move the pieces on the board?
(1 answer)
Drag multiple sprites with different "update ()" methods from the same Sprite class in Pygame
(2 answers)
How can I drag more than 2 images in PyGame?
(1 answer)
How do I add a rubber band for mouse dragging in PyGame? [closed]
(1 answer)
Closed 23 days ago.
I want to be able to click on the box and then click somewhere else and have it move to that location. I have no idea how to do it. Some of the ways I tried work but they only work for one image(if i have 2 or more boxes it wont work). Can you modify this code so when the box is clicked it becomes selected, then if anywhere else on the screen is clicked, the box will move to that new location?
Here is the code:
import pygame # Import the pygame module
# Initialize pygame
pygame.init()
# Set the screen size
screen = pygame.display.set_mode((512, 512))
# Set the title of the screen
pygame.display.set_caption("Screen")
image = pygame.transform.scale(pygame.image.load('image.png'),(64,64))
# Run the game loop
running = True
while running: # Main game loop
for event in pygame.event.get(): # Check for events
if event.type == pygame.QUIT: # If the user clicks the close button
running = False # Exit the game loop
# Clear the screen
screen.fill((255, 255, 255))
# Draw the image#
screen.blit(image,(224,224))
# Update the screen
pygame.display.update()
# Quit pygame
pygame.quit()

Pygame Window opens then immediately cloeses [duplicate]

This question already has answers here:
Why is my PyGame application not running at all?
(2 answers)
Closed last year.
I am coming back to pygame after around one and a half months of taking a break.
I tried to open and create a window I tried to run it and the window immediately closed.
This is all of the code:
import pygame
pygame.init()
screen_x = 230
screen_y = 230
display = pygame.display.set_mode ((screen_x, screen_y))
I am using VSCode if that does anything, this is the first time I have used VSCode so if I do not do something right I may not know.
You need an event loop, or else the application will close immediately.
Here is some starter code to do this:
import pygame
# screen object(width,height)
screen_x = 230
screen_y = 230
screen = pygame.display.set_mode((screen_x, screen_y))
# Set the caption of the screen
pygame.display.set_caption('Title')
# Variable to keep our game loop running
running = True
# game loop
while running:
# for loop through the event queue
for event in pygame.event.get():
# Check for QUIT event
if event.type == pygame.QUIT:
running = False

Pygame, the window becomes irresponsive when I try to click it

I'm working on a game with Pygame and it was going well...until it decided to not respond. Here's my code:(sorry if the formatting doesn't work im new to stackoverflow)
#MODULES USED (use from to make calling functions easier)
from random import *
from pygame import *
import pygame
from pygame.locals import *
pygame.init()
from time import *
#INITIALISE THE PYGAME WINDOW
pygame.event.pump()
screen = display.set_mode([500, 500])
blue = [230, 242, 255]
screen.fill(blue)
pygame.display.update()
default = pygame.image.load("default.jpg")
screen.blit(default, (0,0))
pygame.display.update()
click = pygame.mouse.get_pressed()
#BASIC HEXAPAWN
#ALL POSSIBLE COMPUTER'S MOVE BOARDS AS ARRAY HERE
#TThe moves from the board images are left to right
class Board:
def __init__(self, board, moves):
self.board = board
self.moves = moves
boards1 = [pygame.image.load("a1.jpg"), pygame.image.load("a2.jpg"), pygame.image.load("a3.jpg")] #move1 boards
#irrelevant stuff removed, just initialising the other boards.
#GAME MAIN LOOP
while True:
#START GAME - 1st move
print("You play as O, computer is X")
currentboard = "O O O\n# # #\nX X X"
print(currentboard)
#PLAYER MOVE 1
screen.blit(boards1[0], (0, 250))
pygame.display.update()
if boards1[0].get_rect().collidepoint(pygame.mouse.get_pos()) and click:
screen.blit(boards1[0], (0,0))
pmove = 0
#note: I haven't added the other board options yet.
currentboard = boards1[pmove]
#[insert more unnecessary code here]
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
break
pygame.quit()
Basically whenever I run the code, the Pygame window looks alright, but when I try to click on the image it just stops responding. Also the window is always stuck on a loading cursor, idk why.
I've tried everything I could find but, nope, not working.
If anyone can help then I'd appreciate it.
Thanks :)
Eleeza
edit:i didnt know others could edit my posts too
Clearing some stuff up, when I ran my code, there were no errors, no Traceback the only problem is the unresponsive thing.
Also sorry im really bad at explaining things :/
There are a few things going on, but the main one is that you have you click variable set only once when the program starts.
Move click = pygame.mouse.get_pressed() inside of the main loop.
If you do that and it still hangs, you should show the rest of your code.
Also, the full code is not there, so I can't be 100% sure, but I don't think that break should be there.

Tab out of Pygame fullscreen window without crashing it

So I'm using Pygame to create a fancy display for a program I am writing. I chose Pygame because it's easy to get started and does a great job with animations. I want the display to be as big as I can make it so as much information can be shown as possible. Here is the kicker however, I still want to be able to get to the console of the program.
Pygame forces a fullscreen window to the front, so you cant tab out, and moving the windows to another windows desktop crashes the display. I would do a key trick to switch the pygame mode, but I cannot use pygame.event.get() because of how the program the threaded.
Is there a way to make it a full-screen window so that I can tab out and leave it up in the background? I dont really want it to just be a normal window because it is not as big that way.
The display crashes after I tab out and back in, here is what that looks like:
I also get a non-zero exit code: -805306369 (0xCFFFFFFF)
Here is a broken down version of the code that still gives me this error, you'll notice there are some things in here you wouldn't have if this was your full program, but I wanted to retain as much architecture as I could.
import pygame
import os
BACKGROUND = (9, 17, 27)
os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0"
pygame.init()
pygame.font.init()
infoObject = pygame.display.Info()
SIZE = (infoObject.current_w, infoObject.current_h)
X_CENTER = SIZE[0]/2
Y_CENTER = SIZE[1]/2
# create a borderless window that's as big as the entire screen
SCREEN = pygame.display.set_mode((SIZE[0], SIZE[1]), pygame.NOFRAME)
clock = pygame.time.Clock()
TextFont = pygame.font.SysFont('Courant', 30)
class DisplayState:
state = type(bool)
def __init__(self):
self.state = True
def get_state(self):
return self.state
def change_state(self, new_state):
self.state = new_state
def main(display_state_object):
running = True
while running:
if display_state_object.get_state():
SCREEN.fill(BACKGROUND)
pygame.display.flip()
else:
return 1
return
if __name__ == "__main__":
main(DisplayState())
EDIT
I think it is a multi-threading problem! See this code:
Produces Error
def start_display():
display(params)
def display(params):
pygame loop
if __name__ == "__main__":
display_thread = threading.Thread(target=start_display)
display_thread.start()
Does not produce error
def display(params):
pygame loop
if __name__ == "__main__":
display_thread = threading.Thread(target=display(params))
display_thread.start
# marker
One problem with the version that does work, the program does not seem to be continuing forwards outside the thread (ie the marker is never reached). Is this how the threading library works? It may explain why I had the middle man function present. Maybe this is a different problem and deserves its own question?
EDIT
Setting up the thread like this allows the main thread to continue, but brings back the pygame error:
threading.Thread(target=display, args=(DisplayState(),))
There's no easy way to do this on windows/sdl using the real fullscreen mode, and the usual way to solve this is to use a borderless window.
Here's how to create such a "fake" fullscreen window in pygame:
import pygame
import os
# you can control the starting position of the window with the SDL_VIDEO_WINDOW_POS variable
os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0"
pygame.init()
# now let's see how big our screen is
info = pygame.display.Info()
# and create a borderless window that's as big as the entire screen
screen = pygame.display.set_mode((info.current_w, info.current_h), pygame.NOFRAME)
You have to call one of the pygame event functions (e.g. pygame.event.pump() or pygame.event.get()) each frame or the window will become unresponsive and the program will appear to have crashed. If you call one of those functions, you should be able to press Alt+Tab (in Windows) to get back to the desktop without crashing the program (if you select the desktop, the window will be minimized and if you select another window, it will just be brought to the front).
def main(display_state_object):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
# Press Esc to quit.
if event.key == pygame.K_ESCAPE:
running = False
if display_state_object.get_state():
SCREEN.fill(BACKGROUND)
pygame.display.flip()
else:
return 1
return

Python pygame window keeps crashing

Whenever I run my code the Python Window that shows up does not respond.
Is there something wrong with my code or do I have to re-install pygame and python?
I get a black pygame window and then it turns white and says not responding?
Also I am new to this so please make this as simple as possible. I tried looking everywhere for the answer but could not get it in a way that I could understand.
Please help me out. Thanks :)
1 - Import library
import pygame
from pygame.locals import *
2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
3 - Load Images
player = pygame.images.load("resources/images/dude.png")
4 - keep looping through
while 1:
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the screen elements
screen.blit(player, (100,100))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
Don't import pygame.locals. It is actually unnecessary, since you are already importing pygame.
Also, as #furas said, it should be:
player = pygame.image.load("resources/images/dude.png")
Not:
player = pygame.images.load("resources/images/dude.png")
This will clear up some of the problems in your code.
From my personal experience,if you run pygame code from IDLE it often does not respond at all.Try saving your project as a .py file and then run it with python.exe.It always works for me.
And as furas said use
player = pygame.image.load("resources/images/dude.png")
instead of
player = pygame.images.load("resources/images/dude.png")
Replace that for loop with this
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

Categories

Resources