Skip to content

Instantly share code, notes, and snippets.

@hangj
Last active July 6, 2021 08:11
Show Gist options
  • Save hangj/98398f3409c438d86507c2789fa87eb2 to your computer and use it in GitHub Desktop.
Save hangj/98398f3409c438d86507c2789fa87eb2 to your computer and use it in GitHub Desktop.
python 调节 Windows 系统音量
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pip3 install pycaw -i https://pypi.douban.com/simple
# https://docs.microsoft.com/en-us/windows/win32/api/endpointvolume/nf-endpointvolume-iaudioendpointvolume-getvolumerange
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
def getVolume():
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
v = volume.GetMasterVolumeLevel()
vmin,vmax,vinc = volume.GetVolumeRange()
return 100 * (v - vmin)/(vmax - vmin)
def setVolume(v):
if v < 0 or v > 100:
return
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
vmin,vmax,vinc = volume.GetVolumeRange()
volume.SetMasterVolumeLevel(vmin + v*(vmax-vmin)/100.0, None)
# 设置静音,mute为1代表是静音,为0代表取消静音
# volume.SetMute(0, None)
def main():
import sys
if len(sys.argv) == 1:
return print(getVolume())
setVolume(float(sys.argv[1]))
if __name__ == '__main__':
main()
1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment