我在使用winsound和tqdm时遇到了一些问题。我使用进度条制作了一个地下控制系统,该进度条显示了两个站点之间的距离,并播放名为该站点名称的winsound。显示进度条,但没有声音。
from tqdm import tqdm
import time
import winsound
for i in tqdm(range(100)):
time.sleep(0.02)
winsound.PlaySound("Nastepna.wav", winsound.SND_ASYNC)
但是,当我这样做时:
from tqdm import tqdm
import time
import winsound
winsound.PlaySound("Nastepna.wav", winsound.SND_ASYNC)
for i in tqdm(range(100)):
time.sleep(0.02)
声音播放没有问题。
最佳答案
从winsound
上的SND_ASYNC
documentation:
winsound.SND_ASYNC Return immediately, allowing sounds to play asynchronously.
So the SND_ASYNC
flag makes the call to PlaySound
asynchronous. That is, it does not wait for the sound to complete before returning. This works fine when you make the call first and then effectively sleep for 2 seconds displaying the progress bar, because the sound has time to play out while the program continues to execute.
But when you play the sound in this way after the work of the program is done, the PlaySound
function immediately returns and then the program has nothing else to do, so it exits, providing no time for the sound to play.
You can change this behavior by passing the winsound.SND_FILENAME
flag to PlaySound
instead, which will make the call synchronous, waiting for the sound to finish playing before returning:
from tqdm import tqdm
import time
import winsound
for i in tqdm(range(100)):
time.sleep(0.02)
winsound.PlaySound("Nastepna.wav", winsound.SND_FILENAME)
关于python - Python TQDM进度栏阻止Winsound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53673399/