window in pygame freeze while waiting - python

I'm using pygame for my game and its online but the problem is that whenever the main loop of the game waits for the socket from the server its freezes.
so unless you are doing your turn, the client wait for a socket from the server and its doing nothing while waiting and freeze until its get the socket and do its turn.
So I read few answers and solutions on this site and on some others and from what I understood after 5 seconds of doing nothing the OS thinks the window (locked itself)? so I created the thread keep_run but it does not make any change and the window still freeze while its not his turn.
Also to mention the server works with select library if its help in anyway because keep_run() is the only thread I used.
I did not include many lines in my code because there are too much but its a basic conclusion of the important stuff that maybe cause it?
import sockets
import pygame
from threading import Thread
def keep_run():
clock = pygame.time.Clock()
fps = 60
while True:
pygame.event.pump()
clock.tick(fps)
pygame.init()
keep_running = Thread(target=keep_run)
keep_running.setDaemon(True)
keep_running.start()
while Game_run:
#the main loop
server_command = client_socket.recv(1024)
if server_command == "move":
# make your turn
do_turn()
elif server_command == "over":
# finish the game
finish_game()
image of the example: https://i.stack.imgur.com/b4Qx8.png

You must call pygame.event.pump() (which is implicitly called by pygame.event.get(), pygame.event.clear(), pygame.event.poll(), pygame.event.wait() or pygame.event.peek()) regularly in the thread that initialized the video subsystem (Pygame is built on SDL, hence the link to SDL documentation).
I would also suggest that you don't use pygame.event.pump() and instead handle all events properly with pygame.event.get() or pygame.event.poll(). More about this here.

Related

pygame window takes forever to start

So I'm following the alien invasion project from python crash course, at the beginning the book teaches how to open a simple window with a specific background color. I literally copy-pasted the code from the book and it still does not work.
import pygame
import sys
from settings import Settings
def run_game():
# Initialize game and create a screen object.
pygame.init()
# Init settings
my_settings = Settings()
screen = pygame.display.set_mode((my_settings.screen_widht, my_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
# Start the main loop for the game.
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw the screen during each pass through the loop.
screen.fill(my_settings.bg_color)
# Make the most recently drawn screen visible.
pygame.display.flip()
run_game()
EDIT: To clarify, I'm not saying the code doesn't work, it works without errors but takes a minute to open... it's something with my system, but I don't know what it is, that's why I'm asking
Edit2: I realized that if I remove pygame.init() the window opens instantly, not sure what it means
pygame.init() initializes all pygame modules. This may take some time on some systems. If you don't need all pygame modules, just leave it out. For the display and event handling it is not necessary to call pygame.init() at all. If you need other modules, you can itialize them separately (e.g. pygame.font.init(), pygame.mixer.init()).
See pygame.init()
Initialize all imported pygame modules. No exceptions will be raised if a module fails, but the total number if successful and failed inits will be returned as a tuple. You can always initialize individual modules manually, but pygame.init()initialize all imported pygame modules is a convenient way to get everything started. The init() functions for individual modules will raise exceptions when they fail.
You may want to initialize the different modules separately to speed up your program or to not use modules your game does not require.

when adding music in line 13 it comes up with the error "pygame.error: Failed loading libvorbisfile-3.dll: The specified module could not be found" [duplicate]

I'm trying to play sound files (.wav) with pygame but when I start it I never hear anything.
This is the code:
import pygame
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")
sounda.play()
I also tried using channels but the result is the same
For me (on Windows 7, Python 2.7, PyGame 1.9) I actually have to remove the pygame.init() call to make it work or if the pygame.init() stays to create at least a screen in pygame.
My example:
import time, sys
from pygame import mixer
# pygame.init()
mixer.init()
sound = mixer.Sound(sys.argv[1])
sound.play()
time.sleep(5)
sounda.play() returns an object which is necessary for playing the sound. With it you can also find out if the sound is still playing:
channela = sounda.play()
while channela.get_busy():
pygame.time.delay(100)
I had no sound from playing mixer.Sound, but it started to work after i created the window, this is a minimal example, just change your filename, run and press UP key to play:
WAVFILE = 'tom14.wav'
import pygame
from pygame import *
import sys
mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
pygame.init()
print pygame.mixer.get_init()
screen=pygame.display.set_mode((400,400),0,32)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key==K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key==K_UP:
s = pygame.mixer.Sound(WAVFILE)
ch = s.play()
while ch.get_busy():
pygame.time.delay(100)
pygame.display.update()
What you need to do is something like this:
import pygame
import time
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")
sounda.play()
time.sleep (20)
The reason I told the program to sleep is because I wanted a way to keep it running without typing lots of code. I had the same problem and the sound didn't play because the program closed immediately after trying to play the music.
In case you want the program to actually do something just type all the necessary code but make sure it will last long enough for the sound to fully play.
import pygame, time
pygame.mixer.init()
pygame.init()
sounda= pygame.mixer.Sound("beep.wav")
sounda.play()
pygame.init() goes after mixer.init(). It worked for me.
I had the same problem under windows 7. In my case I wasn't running the code as Administrator. Don't ask me why, but opening a command line as administrator fixed it for me.
I think what you need is pygame.mixer.music:
import pygame.mixer
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(open("\windows\media\chimes.wav","rb"))
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print "done"
You missed to wait for the sound to finish. Your application will start playing the sound but will exit immediately.
If you want to play a single wav file, you have to initialize the module and create a pygame.mixer.Sound() object from the file. Invoke play() to start playing the file. Finally, you have to wait for the file to play.
Use get_length() to get the length of the sound in seconds and wait for the sound to finish:
(The argument to pygame.time.wait() is in milliseconds)
import pygame
pygame.mixer.init()
sounda = pygame.mixer.Sound('desert_rustle.wav')
sounda.play()
pygame.time.wait(int(sounda.get_length() * 1000))
Alternatively you can use pygame.mixer.get_busy to test if a sound is being mixed. Query the status of the mixer continuously in a loop.
In the loop, you need to delay the time by either pygame.time.delay or pygame.time.Clock.tick. In addition, you need to handle the events in the application loop. See pygame.event.get() respectively pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
import pygame
pygame.init()
pygame.mixer.init()
sounda = pygame.mixer.Sound('desert_rustle.wav')
sounda.play()
while pygame.mixer.get_busy():
pygame.time.delay(10)
pygame.event.poll()
Your code plays desert_rustle.wav quite fine on my machine (Mac OSX 10.5, Python 2.6.4, pygame 1.9.1). What OS and Python and pygame releases are you using? Can you hear the .wav OK by other means (e.g. open on a Mac's terminal or start on a Windows console followed by the filename/path to the .wav file) to guarante the file is not damaged? It's hard to debug your specific problem (which is not with the code you give) without being able to reproduce it and without having all of these crucial details.
Just try to re-save your wav file to make sure its frequency info. Or you can record a sound to make sure its frequency,bits,size and channels.(I use this method to solve this problem)
I've had something like this happen. Maybe you have the same problem? Try using an absolute path:
import pygame
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("/absolute_path/desert_rustle.wav")
sounda.play()
Where abslute_path is obviously replaced with your actual absolute path ;)
good luck.
import pygame
pygame.init()
sound = pygame.mixer.Sound("desert_rustle.wav")
pygame.mixer.Sound.play(sound)
This will work on python 3
5 years late answer but I hope I can help someone.. :-)
Firstly, you dont need the "pygame.init()"-line.
Secondly, make a loop and play the sound inside that, or else pygame.mixer will start, and stop playing again immediately.
I got this code to work fine on my Raspberry pi with Raspbian OS.
Note that I used a while-loop that continues to loop the sound forver.
import pygame.mixer
pygame.mixer.init()
sounda = pygame.mixer.Sound("desert_rustle.wav")
while True:
sounda.play()
Just try:
import pygame.mixer
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(open("\windows\media\chimes.wav","rb"))
print ""
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print "done"
This should work. You just need to add print ""and the sound will have
had time to load its self.
Many of the posts are running all of this at toplevel, which is why the sound may seem to close. The final method will return while the sound is playing, which closes the program/terminal/process (depending on how called).
What you will eventually want is a probably a class that can call either single time playback or a looping function (both will be called, and will play over each other) for background music and single sound effects.
Here is pattern, that uses a different event loop / run context other than Pygame itself, (I am using tkinter root level object and its init method, you will have to look this up for your own use case) once you have either the Pygame.init() runtime or some other, you can call these methods from your own logic, unless you are exiting the entire runtime, each file playback (either single use or looping)
this code covers the init for ONLY mixer (you need to figure our your root context and where the individual calls should be made for playback, at least 1 level inside root context to be able to rely on the main event loop preventing premature exit of sound files, YOU SHOULD NOT NEED TIME.SLEEP() AT ALL (very anti-pattern here).... ALSO whatever context calls the looping forever bg_music, it will probably be some 'level' or 'scene' or similar in your game/app context, when passing from one 'scene' to the next you will probably want to immediately replace the bg_music with the file for next 'scene', and if you need the fine-grained control stopping the sound_effect objects that are set to play once (or N times)....
from pygame import mixer
bg_music = mixer.Channel(0)
sound_effects = mixer.Channel(1)
call either of these from WITHIN your inner logic loops
effect1 = mixer.Sound('Sound_Effects/'+visid+'.ogg')
sound_effects.play(effect1, 0)
sound1 = mixer.sound('path to ogg or wav file')
bg_music.play(sound1, -1) # play object on this channel, looping forever (-1)
do this:
import pygame
pygame.mixer.init()
pygame.mixer.music.load("desert_rustle.wav")
pygame.mixer.music.play(0)
I think that your problem is that the file is a WAV file.
It worked for me with an MP3. This will probably work on python 3.6.

TypeError: Source object must be a surface [duplicate]

I'm trying to play sound files (.wav) with pygame but when I start it I never hear anything.
This is the code:
import pygame
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")
sounda.play()
I also tried using channels but the result is the same
For me (on Windows 7, Python 2.7, PyGame 1.9) I actually have to remove the pygame.init() call to make it work or if the pygame.init() stays to create at least a screen in pygame.
My example:
import time, sys
from pygame import mixer
# pygame.init()
mixer.init()
sound = mixer.Sound(sys.argv[1])
sound.play()
time.sleep(5)
sounda.play() returns an object which is necessary for playing the sound. With it you can also find out if the sound is still playing:
channela = sounda.play()
while channela.get_busy():
pygame.time.delay(100)
I had no sound from playing mixer.Sound, but it started to work after i created the window, this is a minimal example, just change your filename, run and press UP key to play:
WAVFILE = 'tom14.wav'
import pygame
from pygame import *
import sys
mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
pygame.init()
print pygame.mixer.get_init()
screen=pygame.display.set_mode((400,400),0,32)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key==K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key==K_UP:
s = pygame.mixer.Sound(WAVFILE)
ch = s.play()
while ch.get_busy():
pygame.time.delay(100)
pygame.display.update()
What you need to do is something like this:
import pygame
import time
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")
sounda.play()
time.sleep (20)
The reason I told the program to sleep is because I wanted a way to keep it running without typing lots of code. I had the same problem and the sound didn't play because the program closed immediately after trying to play the music.
In case you want the program to actually do something just type all the necessary code but make sure it will last long enough for the sound to fully play.
import pygame, time
pygame.mixer.init()
pygame.init()
sounda= pygame.mixer.Sound("beep.wav")
sounda.play()
pygame.init() goes after mixer.init(). It worked for me.
I had the same problem under windows 7. In my case I wasn't running the code as Administrator. Don't ask me why, but opening a command line as administrator fixed it for me.
I think what you need is pygame.mixer.music:
import pygame.mixer
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(open("\windows\media\chimes.wav","rb"))
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print "done"
You missed to wait for the sound to finish. Your application will start playing the sound but will exit immediately.
If you want to play a single wav file, you have to initialize the module and create a pygame.mixer.Sound() object from the file. Invoke play() to start playing the file. Finally, you have to wait for the file to play.
Use get_length() to get the length of the sound in seconds and wait for the sound to finish:
(The argument to pygame.time.wait() is in milliseconds)
import pygame
pygame.mixer.init()
sounda = pygame.mixer.Sound('desert_rustle.wav')
sounda.play()
pygame.time.wait(int(sounda.get_length() * 1000))
Alternatively you can use pygame.mixer.get_busy to test if a sound is being mixed. Query the status of the mixer continuously in a loop.
In the loop, you need to delay the time by either pygame.time.delay or pygame.time.Clock.tick. In addition, you need to handle the events in the application loop. See pygame.event.get() respectively pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
import pygame
pygame.init()
pygame.mixer.init()
sounda = pygame.mixer.Sound('desert_rustle.wav')
sounda.play()
while pygame.mixer.get_busy():
pygame.time.delay(10)
pygame.event.poll()
Your code plays desert_rustle.wav quite fine on my machine (Mac OSX 10.5, Python 2.6.4, pygame 1.9.1). What OS and Python and pygame releases are you using? Can you hear the .wav OK by other means (e.g. open on a Mac's terminal or start on a Windows console followed by the filename/path to the .wav file) to guarante the file is not damaged? It's hard to debug your specific problem (which is not with the code you give) without being able to reproduce it and without having all of these crucial details.
Just try to re-save your wav file to make sure its frequency info. Or you can record a sound to make sure its frequency,bits,size and channels.(I use this method to solve this problem)
I've had something like this happen. Maybe you have the same problem? Try using an absolute path:
import pygame
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("/absolute_path/desert_rustle.wav")
sounda.play()
Where abslute_path is obviously replaced with your actual absolute path ;)
good luck.
import pygame
pygame.init()
sound = pygame.mixer.Sound("desert_rustle.wav")
pygame.mixer.Sound.play(sound)
This will work on python 3
5 years late answer but I hope I can help someone.. :-)
Firstly, you dont need the "pygame.init()"-line.
Secondly, make a loop and play the sound inside that, or else pygame.mixer will start, and stop playing again immediately.
I got this code to work fine on my Raspberry pi with Raspbian OS.
Note that I used a while-loop that continues to loop the sound forver.
import pygame.mixer
pygame.mixer.init()
sounda = pygame.mixer.Sound("desert_rustle.wav")
while True:
sounda.play()
Just try:
import pygame.mixer
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(open("\windows\media\chimes.wav","rb"))
print ""
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print "done"
This should work. You just need to add print ""and the sound will have
had time to load its self.
Many of the posts are running all of this at toplevel, which is why the sound may seem to close. The final method will return while the sound is playing, which closes the program/terminal/process (depending on how called).
What you will eventually want is a probably a class that can call either single time playback or a looping function (both will be called, and will play over each other) for background music and single sound effects.
Here is pattern, that uses a different event loop / run context other than Pygame itself, (I am using tkinter root level object and its init method, you will have to look this up for your own use case) once you have either the Pygame.init() runtime or some other, you can call these methods from your own logic, unless you are exiting the entire runtime, each file playback (either single use or looping)
this code covers the init for ONLY mixer (you need to figure our your root context and where the individual calls should be made for playback, at least 1 level inside root context to be able to rely on the main event loop preventing premature exit of sound files, YOU SHOULD NOT NEED TIME.SLEEP() AT ALL (very anti-pattern here).... ALSO whatever context calls the looping forever bg_music, it will probably be some 'level' or 'scene' or similar in your game/app context, when passing from one 'scene' to the next you will probably want to immediately replace the bg_music with the file for next 'scene', and if you need the fine-grained control stopping the sound_effect objects that are set to play once (or N times)....
from pygame import mixer
bg_music = mixer.Channel(0)
sound_effects = mixer.Channel(1)
call either of these from WITHIN your inner logic loops
effect1 = mixer.Sound('Sound_Effects/'+visid+'.ogg')
sound_effects.play(effect1, 0)
sound1 = mixer.sound('path to ogg or wav file')
bg_music.play(sound1, -1) # play object on this channel, looping forever (-1)
do this:
import pygame
pygame.mixer.init()
pygame.mixer.music.load("desert_rustle.wav")
pygame.mixer.music.play(0)
I think that your problem is that the file is a WAV file.
It worked for me with an MP3. This will probably work on python 3.6.

How could I stop or delay a Pygame timer, which is linked to an User event?

I'm new to python, but I'm trying to learn it by myself for a university course.
Therefore I have to program a pygame window that represents a drone fly zone (The drone should fly automated like a search helicopter in a given area and on the window a visual representation of what happens should be displayed...).
How an older version of the pygame window look's like when the virtual drone flies.
So far so good.
Now I have to link the movements of the game-represented drone with the real Tello drone.
I figured out that using threading for the movement commands to the drone is the way to go when the pygame window should run the whole time.
But now I got stuck because I have to delay the automated movements in pygame in order to wait for the drone flight time and response.
I update the pygame window with a clock set to tick(60) in the loop of the game (therefore I created a Clock clock = pygame.time.Clock() in the initialization of the pygame program), but for the automated drone movements I created an Userevent.
The drone movements is trigger like a Snake game via a Userevent witch should be triggered every second.
Therefor I implemented a timer:
self.SCREEN_UPDATE = pygame.USEREVENT
self.screen_update = pygame.time.set_timer(self.SCREEN_UPDATE, 1000).
But now I have to delay the automated movements in pygame every time the drone should do a movement. Otherwise, the pygame program run's too fast for the real-world problem.
(The User event gets starter again before the real drone has finished his command)
I also tried to implement break functions for that, but they do not work.
def break_rotation(self):
print("start waiting")
self.screen_update.time.wait(2000)
#self.screen_update = pygame.time.set_timer(self.SCREEN_UPDATE, 2000)
#pygame.time.wait(2000)
print("end waiting")``
def break_move(self):
print("start waiting")
self.screen_update.time.wait(3000)
#self.screen_update = pygame.time.set_timer(self.SCREEN_UPDATE, 3000)
#pygame.time.wait(3000)
print("end waiting")
I also tried the comment lines. pygame.time.wait()makes the whole pygame wait. But You should still be able to use your keyboard for emergency landings and other stuff.
So I only have to delay the next Userevent, where the hole flypath for the next block / section get's tested for the automated flypath and the program decides to fly forward or should it turn.
Does anyone have an Idear how I could achieve that delay on the timer?
Sadly I also couldn't find some similar problems.
EDIT 1:
#CmdCoder858
I think this code may hold the update back for a couple of seconds.
When using the and operator combined with a passed variable.
if event.type == SCREEN_UPDATE and x == 1:
I also tried using multiple events but that didn't work probably.
if event.type == SCREEN_UPDATE and event.type == drone_task_finished:
Interestingly it ignored the hole and operator this way.
import pygame
import threading
import _thread
import time
def task():
global x
# placeholder for drone task
print('Test thread start')
time.sleep(5) # simulate delay in the task
x = x+1
print('Thread ends')
pygame.event.post(pygame.event.Event(drone_task_finished))
if __name__ == '__main__':
pygame.init()
x = 0
drone_task_finished = pygame.USEREVENT # an integer representing the first user event
drone_task = threading.Thread(target=task) # create a thread with a task function
drone_task.start()
pygame.display.set_caption("Overview of the Search Area")
window = pygame.display.set_mode((500, 300))
SCREEN_UPDATE = pygame.USEREVENT
screen_update = pygame.time.set_timer(SCREEN_UPDATE, 1000)
print('Start event loop')
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == SCREEN_UPDATE and x == 1:
print('Hura Timer paused for 5 sec')
x = 0
drone_task = threading.Thread(target=task) # create a thread with a task function
drone_task.start()
if event.type == SCREEN_UPDATE:
print('Update nach 1sec')
if event.type == drone_task_finished: # detect if a drone_task_finished event has been posted
print('Drone task has finished')
But is there any reason not to use import _thread?
With that, I could call the function multiple times in new threads.
Therefore I have to change the task function to def task(threadName):
Now I could simply use _thread.start_new_thread(task, ("",)) every time the task should be used later on.
From what is sounds like, I would guess you want to wait for an event in another thread whilst keeping the main loop running, in which case I think you should try using pygame.event.post() function. This function is apparently thread safe so as long as it is called from a thread that was started after pygame.init() it should definitely work. You can create a custom event using the pygame.event.custom_type() function, meaning that you can wait for the event to be returned without having to pause the display. Comment below if you have any questions.
Edit:
Adding a code example for clarity:
import pygame
import threading
import time
def task():
# placeholder for drone task
time.sleep(3) # simulate delay in the task
pygame.event.post(pygame.event.Event(drone_task_finished))
if __name__ == '__main__':
pygame.init()
drone_task_finished = pygame.USEREVENT # an integer representing the first user event
drone_task = threading.Thread(target=task) # create a thread with a task function
drone_task.start()
print('Start event loop')
while 1:
for event in pygame.event.get():
if event.type == drone_task_finished: # detect if a drone_task_finished event has been posted
print('Drone task has finished')
Essentially what is happening here is we are creating a task to be completed, then starting the task and continuing with the event loop. Once the task has finished, it will use the pygame.event.post function to tell the main thread that its task has been completed. The main thread can then detect this and proceed accordingly.
Edit 2:
To answer your questions, firstly don't worry about creating an answer to your own question, just editing your original question and mentioning that you have done so in a comment is perfectly fine.
As for using the variable x as a way to delay the execution of another event, this can work but I would recommend keeping x out of the threaded task function, and instead modify it when your main thread detects the drone_task_finished event. This is much better because you don't have to deal with cross-thread variables, so just put that under the if event.type == drone_task_finished: block.
As for using multiple custom events, the reason your code event.type == SCREEN_UPDATE and event.type == drone_task_finished returned True is because that statement is correct, and this is due to how you initialised each event type. You essentially used this code:
drone_task_finished = pygame.USEREVENT
SCREEN_UPDATE = pygame.USEREVENT
However the actual way this should be done is like this:
drone_task_finished = pygame.USEREVENT
SCREEN_UPDATE = pygame.USEREVENT + 1
This is due to how pygame handles event types. Each type is given an integer value, and the built in types get the values up until a certain point. The pygame.USEREVENT constant is an integer representing the first number that is not reserved for other events. This means that creating a new variable to represent an event in pygame should be the integer pygame.USEREVENT, and the second would have the value pygame.USEREVENT + 1. All of this is explained in more detail here.
Finally, as explained in this answer, _thread is an implementation module that should generally be avoided in favour of the threading module, which is what I used in my code. With the threading module, you can create and start a new thread using this code:
drone_task = threading.Thread(target=task)
drone_task.start()
The threading.Thread class also has an optional arguments parameter, meaning it is easy to pass in all the arguments you need to the new thread. You can find more information on how this all works in the documentation.

Pygame wont stream audio over bluetooth but other applications will [duplicate]

I'm trying to play sound files (.wav) with pygame but when I start it I never hear anything.
This is the code:
import pygame
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")
sounda.play()
I also tried using channels but the result is the same
For me (on Windows 7, Python 2.7, PyGame 1.9) I actually have to remove the pygame.init() call to make it work or if the pygame.init() stays to create at least a screen in pygame.
My example:
import time, sys
from pygame import mixer
# pygame.init()
mixer.init()
sound = mixer.Sound(sys.argv[1])
sound.play()
time.sleep(5)
sounda.play() returns an object which is necessary for playing the sound. With it you can also find out if the sound is still playing:
channela = sounda.play()
while channela.get_busy():
pygame.time.delay(100)
I had no sound from playing mixer.Sound, but it started to work after i created the window, this is a minimal example, just change your filename, run and press UP key to play:
WAVFILE = 'tom14.wav'
import pygame
from pygame import *
import sys
mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
pygame.init()
print pygame.mixer.get_init()
screen=pygame.display.set_mode((400,400),0,32)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key==K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key==K_UP:
s = pygame.mixer.Sound(WAVFILE)
ch = s.play()
while ch.get_busy():
pygame.time.delay(100)
pygame.display.update()
What you need to do is something like this:
import pygame
import time
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")
sounda.play()
time.sleep (20)
The reason I told the program to sleep is because I wanted a way to keep it running without typing lots of code. I had the same problem and the sound didn't play because the program closed immediately after trying to play the music.
In case you want the program to actually do something just type all the necessary code but make sure it will last long enough for the sound to fully play.
import pygame, time
pygame.mixer.init()
pygame.init()
sounda= pygame.mixer.Sound("beep.wav")
sounda.play()
pygame.init() goes after mixer.init(). It worked for me.
I had the same problem under windows 7. In my case I wasn't running the code as Administrator. Don't ask me why, but opening a command line as administrator fixed it for me.
I think what you need is pygame.mixer.music:
import pygame.mixer
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(open("\windows\media\chimes.wav","rb"))
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print "done"
You missed to wait for the sound to finish. Your application will start playing the sound but will exit immediately.
If you want to play a single wav file, you have to initialize the module and create a pygame.mixer.Sound() object from the file. Invoke play() to start playing the file. Finally, you have to wait for the file to play.
Use get_length() to get the length of the sound in seconds and wait for the sound to finish:
(The argument to pygame.time.wait() is in milliseconds)
import pygame
pygame.mixer.init()
sounda = pygame.mixer.Sound('desert_rustle.wav')
sounda.play()
pygame.time.wait(int(sounda.get_length() * 1000))
Alternatively you can use pygame.mixer.get_busy to test if a sound is being mixed. Query the status of the mixer continuously in a loop.
In the loop, you need to delay the time by either pygame.time.delay or pygame.time.Clock.tick. In addition, you need to handle the events in the application loop. See pygame.event.get() respectively pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
import pygame
pygame.init()
pygame.mixer.init()
sounda = pygame.mixer.Sound('desert_rustle.wav')
sounda.play()
while pygame.mixer.get_busy():
pygame.time.delay(10)
pygame.event.poll()
Your code plays desert_rustle.wav quite fine on my machine (Mac OSX 10.5, Python 2.6.4, pygame 1.9.1). What OS and Python and pygame releases are you using? Can you hear the .wav OK by other means (e.g. open on a Mac's terminal or start on a Windows console followed by the filename/path to the .wav file) to guarante the file is not damaged? It's hard to debug your specific problem (which is not with the code you give) without being able to reproduce it and without having all of these crucial details.
Just try to re-save your wav file to make sure its frequency info. Or you can record a sound to make sure its frequency,bits,size and channels.(I use this method to solve this problem)
I've had something like this happen. Maybe you have the same problem? Try using an absolute path:
import pygame
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("/absolute_path/desert_rustle.wav")
sounda.play()
Where abslute_path is obviously replaced with your actual absolute path ;)
good luck.
import pygame
pygame.init()
sound = pygame.mixer.Sound("desert_rustle.wav")
pygame.mixer.Sound.play(sound)
This will work on python 3
5 years late answer but I hope I can help someone.. :-)
Firstly, you dont need the "pygame.init()"-line.
Secondly, make a loop and play the sound inside that, or else pygame.mixer will start, and stop playing again immediately.
I got this code to work fine on my Raspberry pi with Raspbian OS.
Note that I used a while-loop that continues to loop the sound forver.
import pygame.mixer
pygame.mixer.init()
sounda = pygame.mixer.Sound("desert_rustle.wav")
while True:
sounda.play()
Just try:
import pygame.mixer
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(open("\windows\media\chimes.wav","rb"))
print ""
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print "done"
This should work. You just need to add print ""and the sound will have
had time to load its self.
Many of the posts are running all of this at toplevel, which is why the sound may seem to close. The final method will return while the sound is playing, which closes the program/terminal/process (depending on how called).
What you will eventually want is a probably a class that can call either single time playback or a looping function (both will be called, and will play over each other) for background music and single sound effects.
Here is pattern, that uses a different event loop / run context other than Pygame itself, (I am using tkinter root level object and its init method, you will have to look this up for your own use case) once you have either the Pygame.init() runtime or some other, you can call these methods from your own logic, unless you are exiting the entire runtime, each file playback (either single use or looping)
this code covers the init for ONLY mixer (you need to figure our your root context and where the individual calls should be made for playback, at least 1 level inside root context to be able to rely on the main event loop preventing premature exit of sound files, YOU SHOULD NOT NEED TIME.SLEEP() AT ALL (very anti-pattern here).... ALSO whatever context calls the looping forever bg_music, it will probably be some 'level' or 'scene' or similar in your game/app context, when passing from one 'scene' to the next you will probably want to immediately replace the bg_music with the file for next 'scene', and if you need the fine-grained control stopping the sound_effect objects that are set to play once (or N times)....
from pygame import mixer
bg_music = mixer.Channel(0)
sound_effects = mixer.Channel(1)
call either of these from WITHIN your inner logic loops
effect1 = mixer.Sound('Sound_Effects/'+visid+'.ogg')
sound_effects.play(effect1, 0)
sound1 = mixer.sound('path to ogg or wav file')
bg_music.play(sound1, -1) # play object on this channel, looping forever (-1)
do this:
import pygame
pygame.mixer.init()
pygame.mixer.music.load("desert_rustle.wav")
pygame.mixer.music.play(0)
I think that your problem is that the file is a WAV file.
It worked for me with an MP3. This will probably work on python 3.6.

Categories