Python + Winsound-检查是否正在播放音频文件 [英] Python + winsound - check whether an audio file is being played

查看:121
本文介绍了Python + Winsound-检查是否正在播放音频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以检查是否正在使用winsound播放音频文件?

Is there a way to check whether an audio file is being played using winsound?

这个想法是在后台播放音乐,而用户可以通过终端输入数据.为了实现这一点,我决定使用SND_ASYNC.

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?

推荐答案

使用 winsound 无法做到这一点;这是一个非常简单,极简的模块.

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()

这篇关于Python + Winsound-检查是否正在播放音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆