You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取PC当前音量水平?无可用实现库,寻求技术帮助

获取电脑音量水平的可行方案

根据不同操作系统,以下是直接可用的实现方案:

Windows

使用pycaw库(专门针对Windows音频控制):

  1. 安装库:
pip install pycaw
  1. 获取主音量的代码示例:
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调用)

  1. 安装库:
pip install pyobjc
  1. 代码示例:
from AppKit import NSApplication, NSSound

def get_mac_volume():
    volume = NSSound.systemVolume()
    return int(volume * 100)

print(f"当前音量: {get_mac_volume()}%")

Linux(基于PulseAudio)

使用pulsectl库:

  1. 安装库:
pip install pulsectl
  1. 代码示例:
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 11:35:24