Python3.9检测win11扬声器是否正在发出声音使用
时间: 2023-07-22 15:32:10 浏览: 227
你可以使用Python 3.9及以上版本和`pycaw`库来检测Windows 11的扬声器是否正在发出声音。以下是一个示例代码:
```python
import time
from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume, IAudioMeterInformation
def is_speaker_playing():
speakers = AudioUtilities.GetSpeakers()
volume = speakers.Activate(ISimpleAudioVolume._iid_, None, None)
meter = speakers.Activate(IAudioMeterInformation._iid_, None, None)
# 获取当前音量和峰值
current_volume = volume.GetMasterVolume()
peak_volume = meter.GetPeakValue()
# 如果当前音量大于0且峰值大于0.01,则认为正在播放声音
if current_volume > 0 and peak_volume > 0.01:
return True
else:
return False
while True:
if is_speaker_playing():
print("Speaker is playing")
else:
print("Speaker is not playing")
time.sleep(1)
```
这段代码会每秒钟检查一次扬声器是否正在发出声音。如果是,则输出"Speaker is playing",否则输出"Speaker is not playing"。注意,这段代码只适用于Windows系统。同时,你需要确保已经安装了`pycaw`库。你可以使用以下命令来安装最新版本的`pycaw`库:
```
pip install pycaw
```
阅读全文