简体   繁体   中英

Python tqdm progress bar blocks winsound

Im experiencing some problems with winsound and tqdm. Im making an underground controlling system using the progress bar showing the distance between 2 stations and winsound playing the name of the station. The progress bar shows up but there is no sound.

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)

however when I do this:

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)

the sound plays with no problems.

From the winsound documentation on SND_ASYNC :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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