简体   繁体   English

如何在其他代码行同时执行时播放声音?

[英]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
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)

EDIT: I have moved the thread declaration into the loop.编辑:我已将线程声明移动到循环中。 My initial answer had it created outside of the loop, which caused a RuntimeError.我最初的答案是在循环之外创建它,这导致了 RuntimeError。 Learn more here: https://docs.python.org/3/library/threading.html#threading.Thread.start在此处了解更多信息: https : //docs.python.org/3/library/threading.html#threading.Thread.start

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:它被称为异步声音, PlaySound上的winsound.SND_ASYNC标志将让您在代码继续执行时播放声音:

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

From memory, this will give you a single sound channel ie playing other sounds will cut off any currently playing sounds.根据记忆,这会给你一个单一的声道,即播放其他声音会切断任何当前播放的声音。 If more concurrent playback is required, something like PyGame is required.如果需要更多的并发播放,则需要像PyGame这样的东西。

There is an optional second argument that is set to True automatically.有一个可选的第二个参数会自动设置为 True。 To play music asynchronously set that argument to False.要异步播放音乐,将该参数设置为 False。

playsound('file',False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM