Stack Developer
Stack Developer

Reputation: 37

PlaySound() slows down process

I have the following code in my program:

self["text"]="✖"              
self["bg"]="red"              
self["relief"] = SUNKEN
self.banged = True
self.lost = True
self.lettersLeft = 0
self.lettersBanged = self.lettB
winsound.PlaySound('sound.wav', winsound.SND_FILENAME)
messagebox.showerror("Letter Banging","Sorry, you lost the game!", parent=self)
for key in self.squares.keys():
    if self.squares[key].value == 3:
        self.squares[key].banged = False
        self.squares[key].expose()

I have just added the winsound.PlaySound('sound.wav', winsound.SND_FILENAME) part and it has slowed down my program. Infact, it plays the sound first and then does what is before it. I am using Python with tKinter. Any suggestions?

Upvotes: 3

Views: 1272

Answers (1)

FabienAndre
FabienAndre

Reputation: 4604

When you alter the property of a widget, such as editing content, background and relief, this change does not appear immediately, they are recorded, and only take effect when you give hand to the mainloop which provoke redraw of your application. This lead to the behavior you observed: the sound is played, then the callback ends and the redraw showing your change happens.

All the time that you will spend in a callback playing the sound, your application will be not responsive. If you estimate your sound is short enough, you can add self.update() somewhere between the UI change you want to show first and the call to PlaySound.

If you want to avoid any unresponsiveness in your app, you can play the sound in another thread

sound_thread = threading.Thread(target=lambda:winsound.PlaySound('sound.wav', winsound.SND_FILENAME))
sound_thread.start()

Upvotes: 1

Related Questions