如何在其他代码行同时执行时播放声音? [英] 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)
我试过了:
import time
import winsound
while True:
print ('ligma')
time.sleep(1.5)
winsound.PlaySound("dank", winsound.SND_ALIAS)
但是,它重复了声音然后重复了这个词.我期待它同时重复单词和播放声音.
but, it repeats the sound then repeats the word. I am expecting it to repeat the word and play the sound at the same time.
推荐答案
您需要在另一个线程上播放声音,以便您的其他代码可以同时执行.
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
def play_sound():
winsound.PlaySound("dank", winsound.SND_ALIAS)
while True:
thread = Thread(target=play_sound)
thread.start()
print ('ligma')
time.sleep(1.5)
我已将线程声明移动到循环中.我最初的答案是在循环之外创建它,这导致了 RuntimeError.在此处了解更多信息:https://docs.python.org/3/library/threading.html#threading.Thread.start
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
这篇关于如何在其他代码行同时执行时播放声音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!