-
Notifications
You must be signed in to change notification settings - Fork 67
/
audio_controller_class_example.py
79 lines (66 loc) · 3.14 KB
/
audio_controller_class_example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""
Per session GetMute() SetMute() GetMasterVolume() SetMasterVolume() using
SimpleAudioVolume.
"""
from pycaw.pycaw import AudioUtilities
class AudioController:
def __init__(self, process_name):
self.process_name = process_name
self.volume = self.process_volume()
def mute(self):
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
interface = session.SimpleAudioVolume
if session.Process and session.Process.name() == self.process_name:
interface.SetMute(1, None)
print(self.process_name, "has been muted.") # debug
def unmute(self):
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
interface = session.SimpleAudioVolume
if session.Process and session.Process.name() == self.process_name:
interface.SetMute(0, None)
print(self.process_name, "has been unmuted.") # debug
def process_volume(self):
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
interface = session.SimpleAudioVolume
if session.Process and session.Process.name() == self.process_name:
print("Volume:", interface.GetMasterVolume()) # debug
return interface.GetMasterVolume()
def set_volume(self, decibels):
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
interface = session.SimpleAudioVolume
if session.Process and session.Process.name() == self.process_name:
# only set volume in the range 0.0 to 1.0
self.volume = min(1.0, max(0.0, decibels))
interface.SetMasterVolume(self.volume, None)
print("Volume set to", self.volume) # debug
def decrease_volume(self, decibels):
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
interface = session.SimpleAudioVolume
if session.Process and session.Process.name() == self.process_name:
# 0.0 is the min value, reduce by decibels
self.volume = max(0.0, self.volume - decibels)
interface.SetMasterVolume(self.volume, None)
print("Volume reduced to", self.volume) # debug
def increase_volume(self, decibels):
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
interface = session.SimpleAudioVolume
if session.Process and session.Process.name() == self.process_name:
# 1.0 is the max value, raise by decibels
self.volume = min(1.0, self.volume + decibels)
interface.SetMasterVolume(self.volume, None)
print("Volume raised to", self.volume) # debug
def main():
audio_controller = AudioController("chrome.exe")
audio_controller.set_volume(1.0)
audio_controller.mute()
audio_controller.decrease_volume(0.25)
audio_controller.increase_volume(0.05)
audio_controller.unmute()
if __name__ == "__main__":
main()