Skip to content Skip to sidebar Skip to footer

How Can I Play A Sound While Other Lines Of Code Execute Simultaneously?

I want my code to do this, but with music playing in the background: import time while True: print ('ligma') time.sleep(1.5) I tried this: import time import winsound wh

Solution 1:

You need to play the sound on another thread, so your other code can be executing at the same time.

import time
import winsound
from threading import Thread

defplay_sound():
    winsound.PlaySound("dank", winsound.SND_ALIAS)

whileTrue:
    thread = Thread(target=play_sound)
    thread.start()
    print ('ligma')
    time.sleep(1.5)

EDIT: I have moved the thread declaration into the loop. My initial answer had it created outside of the loop, which caused a RuntimeError. Learn more here: https://docs.python.org/3/library/threading.html#threading.Thread.start

Solution 2:

It's called asynchronous sound, and the winsound.SND_ASYNC flag on PlaySound will let you play a sound while your code continues to execute:

winsound.PlaySound("dank", winsound.SND_ALIAS|winsound.SND_ASYNC)

From memory, this will give you a single sound channel i.e. playing other sounds will cut off any currently playing sounds. If more concurrent playback is required, something like PyGame is required.

Solution 3:

There is an optional second argument that is set to True automatically. To play music asynchronously set that argument to False.

playsound('file',False)

Post a Comment for "How Can I Play A Sound While Other Lines Of Code Execute Simultaneously?"