我正在开发一个项目,需要在Python中获取当前系统音频输出级别。基本上,我想知道在Linux系统上使用Python时扬声器正在播放的声音有多响。我不需要知道扬声器的确切音量水平,我要的是相对音量。我在网上没有找到任何好的资源。
我正在开发一个项目,需要在Python中获取当前系统音频输出级别。基本上,我想知道在Linux系统上使用Python时扬声器正在播放的声音有多响。我不需要知道扬声器的确切音量水平,我要的是相对音量。我在网上没有找到任何好的资源。
看到你的问题并了解到我无法在macOS上构建pyalsaaudio
,我想提供一个额外的答案,特别是对于如何在macOS上完成这个操作,因为它没有以跨平台的方式抽象出来。
(我知道这对你的直接用例不会有帮助,但我有一种预感,我不是唯一一个会碰到这个问题并寻求我们也能运行的解决方案的Mac用户。)
在macOS上,您可以通过运行一个小的AppleScript 获取输出音量:
$ osascript -e 'get volume settings'
output volume:13, input volume:50, alert volume:17, output muted:false
import re
import subprocess
def get_speaker_output_volume():
"""
Get the current speaker output volume from 0 to 100.
Note that the speakers can have a non-zero volume but be muted, in which
case we return 0 for simplicity.
Note: Only runs on macOS.
"""
cmd = "osascript -e 'get volume settings'"
process = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
output = process.stdout.strip().decode('ascii')
pattern = re.compile(r"output volume:(\d+), input volume:(\d+), "
r"alert volume:(\d+), output muted:(true|false)")
volume, _, _, muted = pattern.match(output).groups()
volume = int(volume)
muted = (muted == 'true')
return 0 if muted else volume
>>> # 2/16 clicks
>>> vol = get_speaker_output_volume()
>>> print(f'Volume: {vol}%')
Volume: 13%
>>> # 2/16 clicks + muted
>>> get_speaker_output_volume()
0
>>> # 16/16 clicks
>>> get_speaker_output_volume()
100
pip install pyalsaaudio
,然后获取音量:>>> import alsaaudio
>>> m = alsaaudio.Mixer()
>>> vol = m.getvolume()
>>> vol
[50L]
注意:此代码是从链接答案的后半部分复制而来。我使用的是Mac电脑,因此无法在macOS上构建库,但乍一看它似乎提供了Linux上当前系统音频输出级别。