如何使用 Python 设置 Windows 音频音量
我们可以使用 pycaw 库通过 Python 设置 Windows 音频音量。
首先,我们使用以下命令安装库
install_pycaw.sh
pip install pycaw注意:pycaw 不适用于 WSL(Windows Subsystem for Linux)!你实际上需要在 Windows 上运行的 Python 环境中安装它。我推荐 Anaconda。
现在我们可以使用此脚本将音量设置为当前音量的一半:
set_windows_volume.py
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
import math
# 使用 PyCAW 获取默认音频设备
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
# 获取当前音量
currentVolumeDb = volume.GetMasterVolumeLevel()
volume.SetMasterVolumeLevel(currentVolumeDb - 6.0, None)
# 注意:-6.0 dB = 一半音量!If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow