python獲取並修改電腦音量


功能

簡單來說就是運行程序可以獲取當前電腦的系統音量,然后可以進行修改

安裝

pip install pycaw

使用

#! /usr/bin/env python
# -*- coding: utf-8 -*-#

# -------------------------------------------------------------------------------
# Name:         修改電腦音量
# Author:       yunhgu
# Date:         2021/7/7 9:32
# Description: 
# -------------------------------------------------------------------------------
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume

devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))

# 判斷是否靜音,mute為1代表是靜音,為0代表不是靜音
mute = volume.GetMute()
if mute == 1:
    print('當前是靜音狀態')
else:
    print('當前是非靜音狀態')

# 獲取音量值,0.0代表最大,-65.25代表最小
vl = volume.GetMasterVolumeLevel()
print('當前音量值為%s' % vl)

# 獲取音量范圍,我的電腦經測試是(-65.25, 0.0, 0.03125),第一個應該代表最小值,第二個代表最大值,第三個不知道是干嘛的。也就是音量從大到小是0.0到-65.25這個范圍
vr = volume.GetVolumeRange()
print('當前音量值為%s' % str(vr))

# 設置音量, 比如-13.6代表音量是40,0.0代表音量是100
# -4.3 為75%
# -10.3 為50%
volume.SetMasterVolumeLevel(-10.3, None)
print('已設置音量為40%')
# 音量對應關系
0% 對應 -65.25
55% 對應 -8.92

{0: -65.25, 1: -56.99, 2: -51.67, 3: -47.74, 4: -44.62, 5: -42.03, 6: -39.82, 7: -37.89, 8: -36.17, 9: -34.63, 10: -33.24,
 11: -31.96, 12: -30.78, 13: -29.68, 14: -28.66, 15: -27.7, 16: -26.8, 17: -25.95, 18: -25.15, 19: -24.38, 20: -23.65,
 21: -22.96, 22: -22.3, 23: -21.66, 24: -21.05, 25: -20.46, 26: -19.9, 27: -19.35, 28: -18.82, 29: -18.32, 30: -17.82,
 31: -17.35, 32: -16.88, 33: -16.44, 34: -16.0, 35: -15.58, 36: -15.16, 37: -14.76, 38: -14.37, 39: -13.99, 40: -13.62,
 41: -13.26, 42: -12.9, 43: -12.56, 44: -12.22, 45: -11.89, 46: -11.56, 47: -11.24, 48: -10.93, 49: -10.63, 50: -10.33,
 51: -10.04, 52: -9.75, 53: -9.47, 54: -9.19, 55: -8.92, 56: -8.65, 57: -8.39, 58: -8.13, 59: -7.88, 60: -7.63,
 61: -7.38, 62: -7.14, 63: -6.9, 64: -6.67, 65: -6.44, 66: -6.21, 67: -5.99, 68: -5.76, 69: -5.55, 70: -5.33,
 71: -5.12, 72: -4.91, 73: -4.71, 74: -4.5, 75: -4.3, 76: -4.11, 77: -3.91, 78: -3.72, 79: -3.53, 80: -3.34,
 81: -3.15, 82: -2.97, 83: -2.79, 84: -2.61, 85: -2.43, 86: -2.26, 87: -2.09, 88: -1.91, 89: -1.75, 90: -1.58,
 91: -1.41, 92: -1.25, 93: -1.09, 94: -0.93, 95: -0.77, 96: -0.61, 97: -0.46, 98: -0.3, 99: -0.15, 100: 0.0}

修改mac電腦音量

首先安裝applescript,在命令行輸入:
pip install applescript

代碼如下:
import applescript
applescript.run('set volume output volume 0')# 設置音量為0
applescript.run('set volume output volume 100')# 設置音量為100


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM