如何在Python中获取系统输出音量?

3

我正在开发一个项目,需要在Python中获取当前系统音频输出级别。基本上,我想知道在Linux系统上使用Python时扬声器正在播放的声音有多响。我不需要知道扬声器的确切音量水平,我要的是相对音量。我在网上没有找到任何好的资源。


这个库pyalsaaudio和以下两个问题可能会对你有所帮助:https://stackoverflow.com/questions/11553131/get-system-volume-sound-level-in-linux-using-python 和 https://askubuntu.com/questions/689521/control-volume-using-python-script。 - Taylor D. Edmiston
1
我感谢Taylor的评论,但是这两个答案都是关于改变系统音量级别的。我想知道系统当前的音量有多大。例如:如果没有播放任何内容,我希望返回0。如果正在播放某些内容,我想要该流的当前音频级别。谢谢。 - Corey Campbell
我在下面添加了一个更具体的答案(有点长,无法放在评论中)。 - Taylor D. Edmiston
你找到解决方案了吗? - HappyFace
2个回答

3

简而言之-获取macOS离散系统输出音量的替代方法。

看到你的问题并了解到我无法在macOS上构建pyalsaaudio,我想提供一个额外的答案,特别是对于如何在macOS上完成这个操作,因为它没有以跨平台的方式抽象出来。

(我知道这对你的直接用例不会有帮助,但我有一种预感,我不是唯一一个会碰到这个问题并寻求我们也能运行的解决方案的Mac用户。)

在macOS上,您可以通过运行一个小的AppleScript 获取输出音量

$ osascript -e 'get volume settings'
output volume:13, input volume:50, alert volume:17, output muted:false

我用Python函数封装了该调用,以将音量+静音状态解析为简单的0-100范围:
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

例如,在MacBook Pro上,不同音量条设置下的情况:
>>> # 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

0
这段代码片段https://askubuntu.com/a/689523/583376提供了你需要的信息吗?
首先,运行pip install pyalsaaudio,然后获取音量:
>>> import alsaaudio
>>> m = alsaaudio.Mixer()
>>> vol = m.getvolume()
>>> vol
[50L]

注意:此代码是从链接答案的后半部分复制而来。我使用的是Mac电脑,因此无法在macOS上构建库,但乍一看它似乎提供了Linux上当前系统音频输出级别。


1
也许“当前音频级别”不是恰当的说法。我正在寻找此页面示例2的输出版本:https://www.programcreek.com/python/example/52624/pyaudio.PyAudio。该程序会记录麦克风随时间变化的音量,我想要扬声器随时间变化的音量。感谢您一直以来的支持。 - Corey Campbell
好的,那么您是在寻找音频输出电平流的连续信号,而不是离散值吗? - Taylor D. Edmiston
是的,我发现音频强度就是我要找的术语。 - Corey Campbell
1
好的,所以您是在寻找实际通过扬声器播放的音频强度,而不是扬声器设置的输出音量? - Taylor D. Edmiston
那是正确的。再次感谢您的帮助。 - Corey Campbell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接