问题
Is there a way to check whether an audio file is being played using winsound?
The idea is that music is played in the background while the user can input data via the terminal. In order to achieve this I decided to use SND_ASYNC.
The thing is though, once the file is finished playing I want it to play another audio file but I have no means of checking when the audio file is actually done playing.
I suppose I could check how long the audio file is and play a different song based on that but I'm guessing there is a simpler way of doing this.
Anyone here know of an easier solution?
回答1:
There is no way to do this with winsound
; it's a dead-simple, minimalist module.
However, there is a pretty simple way to do this indirectly: Create a background thread to play the sound synchronously, then set a flag. Or even just use the thread itself as the flag. For example:
import threading
import winsound
t = threading.Thread(target=winsound.PlaySound, args=[sound, flags])
while True:
do_some_stuff()
t.join(0)
if not t.is_alive():
# the sound has stopped, do something
On the other hand, if all you want to do is play another sound as soon as each one ends, just push them all on a queue:
import queue
import threading
import winsound
def player(q):
while True:
sound, flags = q.get()
winsound.PlaySound(sound, flags)
q = queue.Queue()
t = threading.Thread(target=player, args=[q])
t.daemon = True
q.push(a_sound, some_flags)
q.push(another_sound, some_flags)
do_stuff_for_a_long_time()
来源:https://stackoverflow.com/questions/19976364/python-winsound-check-whether-an-audio-file-is-being-played