volume-loud-on-speak/main.py

84 lines
2.5 KiB
Python

"""
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
"""
import os
import numpy as np
import sounddevice as sd
from subprocess import call, DEVNULL
import time
if os.name == 'posix':
import alsaaudio
elif os.name == 'nt':
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
import math
# See why I hate Windows?
def get_avg():
duration = 3 # seconds
avgvolumes = []
def print_sound(indata, outdata, frames, time, status):
volume_norm = np.linalg.norm(indata)*10
avgvolumes.append(int(volume_norm))
# print(int(volume_norm))
with sd.Stream(callback=print_sound):
sd.sleep(duration * 1000)
totalvol = 0
for vol in avgvolumes:
totalvol = totalvol + vol
avgvol = totalvol / len(avgvolumes)
avgvol = round(avgvol, ndigits=2)
return avgvol
print('Calibrating... Please shut up and don\'t talk.')
avgvol = get_avg()
print(f'Average silent volume is {avgvol}')
if os.name == 'posix':
m = alsaaudio.Mixer()
elif os.name == 'nt':
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
while True:
thing = get_avg()
if thing - avgvol > 1.5:
print("you spoke, volume go up")
bruh = time.time() + 5
if os.name == 'posix':
oldvol = int(m.getvolume()[0])
elif os.name == 'nt':
oldvol = volume.GetMasterVolumeLevel()
while True:
if os.name == 'posix':
call(["amixer", "-D", "pulse", "sset", "Master", "100%", "on"], stdout=DEVNULL)
elif os.name == 'nt':
volume.SetMasterVolumeLevel(0, None)
if time.time() > bruh:
break
if os.name == 'posix':
call(["amixer", "-D", "pulse", "sset", "Master", f"{oldvol}%", "on"], stdout=DEVNULL)
elif os.name == 'nt':
volume.SetMasterVolumeLevel(oldvol, None)
else:
print("you passed the vibe check")