How can I play a sound while other lines of code execute simultaneously?

佐手、 提交于 2021-01-28 00:12:40

问题


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
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.


回答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

def play_sound():
    winsound.PlaySound("dank", winsound.SND_ALIAS)

while True:
    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




回答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.



来源:https://stackoverflow.com/questions/52769618/how-can-i-play-a-sound-while-other-lines-of-code-execute-simultaneously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!