如何获取PC当前音量水平?无可用实现库,寻求技术帮助
获取电脑音量水平的可行方案
根据不同操作系统,以下是直接可用的实现方案:
Windows
使用pycaw库(专门针对Windows音频控制):
- 安装库:
pip install pycaw
- 获取主音量的代码示例:
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume from comtypes import CLSCTX_ALL devices = AudioUtilities.GetSpeakers() interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = interface.QueryInterface(IAudioEndpointVolume) # 获取当前音量(0.0到1.0之间,对应0%-100%) current_volume = volume.GetMasterVolumeLevelScalar() * 100 print(f"当前音量: {current_volume:.1f}%")
macOS
有两种简便方式:
方式1:调用系统命令(无需额外库)
import subprocess def get_mac_volume(): result = subprocess.run( ["osascript", "-e", 'output volume of (get volume settings)'], capture_output=True, text=True ) return int(result.stdout.strip()) print(f"当前音量: {get_mac_volume()}%")
方式2:使用pyobjc库(原生API调用)
- 安装库:
pip install pyobjc
- 代码示例:
from AppKit import NSApplication, NSSound def get_mac_volume(): volume = NSSound.systemVolume() return int(volume * 100) print(f"当前音量: {get_mac_volume()}%")
Linux(基于PulseAudio)
使用pulsectl库:
- 安装库:
pip install pulsectl
- 代码示例:
import pulsectl with pulsectl.Pulse() as pulse: # 获取默认输出设备 default_sink = pulse.get_sink_by_name(pulse.server_info().default_sink_name) # 获取音量范围和当前值,转换为百分比 volume_percent = pulse.volume_get_all_chans(default_sink) * 100 print(f"当前音量: {volume_percent:.1f}%")
内容的提问来源于stack exchange,提问作者ZynthRodak
相关产品推荐
相关产品推荐

