def say(message): try: from win32com.client import constants, Dispatch bot.reply_to(message, '*Воспроизводим...*', parse_mode="Markdown") user_msg = "{0}".format(message.text) devices = AudioUtilities.GetSpeakers() interface = devices.Activate( IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) volume.SetMasterVolumeLevel(-0.0, None) speaker = Dispatch("SAPI.SpVoice") speaker.Speak(user_msg.split("/say")[1]) del speaker bot.send_message(message.chat.id, '*Готово!*', parse_mode="Markdown") except: pass
def start_all_threads(self): if not self.chat_started: print('Trying connection to {}'.format(self.hostAddressBox.text())) self.start_tcp_chat() self.chat_started = True if not self.thread_audio_play.isRunning(): self.start_audio() if not self.thread_video_play.isRunning(): self.start_video_play() for session in AudioUtilities.GetAllSessions(): if session.Process and session.Process.name() == self.process_name: self.volume = session.SimpleAudioVolume self.volume.SetMasterVolume(0.5, None) self.volumeSlider.setValue(50) self.volume_set = True
def getProcessData(): data = [] sessions = AudioUtilities.GetAllSessions() for session in sessions: volume = session._ctl.QueryInterface(ISimpleAudioVolume) if session.Process == None: name = "Systemsounds" else: pid = session.Process.pid handle = win32api.OpenProcess(0x1F0FF, False, pid) executablePath = win32process.GetModuleFileNameEx(handle, 0) name = getProcessName(executablePath) name = trimProcessName(name, 16) masterVolume = volume.GetMasterVolume() data.append([name, round(masterVolume * 100)]) return data
def __init__(self, *args, **kwargs): super(globalPluginHandler.GlobalPlugin, self).__init__(*args, **kwargs) self.readConfiguration() self.devices = AudioUtilities.GetSpeakers() self.interface = self.devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) self.master_volume = cast(self.interface, POINTER(IAudioEndpointVolume)) self.master_volume.SetMasterVolume = self.master_volume.SetMasterVolumeLevelScalar self.master_volume.GetMasterVolume = self.master_volume.GetMasterVolumeLevelScalar self.master_volume.name = _('Master volume') self.master_volume.Process = MasterVolumeFakeProcess(self.master_volume.name) self.master_volume.getDisplayName = lambda: self.master_volume.name gui.settingsDialogs.NVDASettingsDialog.categoryClasses.append(SoundManagerPanel) if hasattr(config, "post_configProfileSwitch"): config.post_configProfileSwitch.register(self.handleConfigProfileSwitch) else: config.configProfileSwitched.register(self.handleConfigProfileSwitch)
def prevprogram(_): global intProgram, programs, program, programsession, programsessionvol intProgram -= 1 if intProgram < 0: intProgram = len(programs) - 1 program = programs[intProgram] sessions = AudioUtilities.GetAllSessions() for session in sessions: if session.Process and session.Process.name() == program: programsession = session programsessionvol = programsession._ctl.QueryInterface( ISimpleAudioVolume) getprogramdisplayname() return "" listprograms(None) return ""
def SetMasterVolume(nr): # Använder Decibel i negativ scala """ nr Percent 0 == 100% -4.30 == 75% -10.3 == 50% -20.4 == 25 -65.2 == 0% """ devices = AudioUtilities.GetSpeakers() interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) # Control volume volume.SetMasterVolumeLevel(nr, None)
def getProcessVolumes(): sessions = AudioUtilities.GetAllSessions() del processes['processes'][:] for session in sessions: if session.Process != None: # If process has a name, continue if session.Process.name( ) not in ignoredProcesses: # Continue if process isn't in the `ignoreProcess` list volume = session.SimpleAudioVolume processes['processes'].append({ 'name': session.Process.name()[:-4], 'volume': int(volume.GetMasterVolume() * 100), 'mute': volume.GetMute() })
def main(): prevData = [0, 0, 0, 0, 0] Spotify_controller = AudioController('Spotify.exe') brave_controller = AudioController('brave.exe') discord_controller = AudioController('Discord.exe') csgo_controller = AudioController('csgo.exe') devices = AudioUtilities.GetSpeakers() interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) master = cast(interface, POINTER(IAudioEndpointVolume)) while True: data = (ser.readline(57).rstrip()).decode() try: dataEval = eval('[' + data + ']')[0] print(dataEval) for i in range(4): if dataEval[i] - 0.01 <= prevData[i] <= dataEval[i] + 0.01: pass else: if dataEval[i] <= 0.005: dataEval[i] == 0 if i == 0: masterVal = -78 * exp(-3.97 * dataEval[i]) + 1.452 master.SetMasterVolumeLevel(masterVal, None) elif i == 1: brave_controller.set_volume(dataEval[i]) csgo_controller.set_volume(dataEval[i]) elif i == 2: Spotify_controller.set_volume(dataEval[i]) pass elif i == 3: discord_controller.set_volume(dataEval[i]) pass elif i == 4: pass else: pass prevData = dataEval except: pass
def savepreset(_): global programs, presets, preset, presetnext sessions = AudioUtilities.GetAllSessions() temppresets = [] for session in sessions: if session.Process and session.Process.name() in programs: vol = session._ctl.QueryInterface( ISimpleAudioVolume).GetMasterVolume() temppresets.append([session.Process.name(), vol]) presets.append(temppresets) preset = len(presets) - 1 presetnext = presets[0] return presets
def volume_set(value_to_set): from ctypes import cast, POINTER from comtypes import CLSCTX_ALL from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume import math # Get default audio device using PyCAW devices = AudioUtilities.GetSpeakers() interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) # Get current volume current_volume_db = volume.GetMasterVolumeLevel() new_db_value = convert_percent_to_db(value_to_set) print("current master volume is: %sdb %sperc" % (current_volume_db, convert_db_to_percent(current_volume_db))) print("new master volume is: %sdb %sperc" % (new_db_value, value_to_set)) volume.SetMasterVolumeLevel(new_db_value, None)
def muter(): while True: sessions = AudioUtilities.GetAllSessions() for session in sessions: volume = session.SimpleAudioVolume # if session.Process: # print(session.Process.name()) if session.Process and session.Process.name() == "Spotify.exe": # print(spotify.song()) try: if spotify.song() == "Advertisement": print("Playing interlude song") volume.SetMute(1, None) AudioPlayer("soundtrack.wav").play(block=True) else: volume.SetMute(0, None) except: continue
def loadpreset(): global preset, presets, presetnext sessions = AudioUtilities.GetAllSessions() for session in sessions: if session.Process and session.Process.name() in possibleprograms: name = session.Process.name() for loading in presets[preset]: if name == loading[0]: session._ctl.QueryInterface( ISimpleAudioVolume).SetMasterVolume(loading[1], None) if preset == len(presets) - 1: presetnext = presets[0] else: presetnext = presets[preset + 1] return ""
def listprograms(_): global programs, possibleprograms, intProgram tempprograms = [] sessions = AudioUtilities.GetAllSessions() for session in sessions: if session.Process and session.Process.name() in possibleprograms: tempprograms.append(session.Process.name()) if len(tempprograms) == 0: raise SkipError() if programs == tempprograms: updatestatus(str(tempprograms) + str(intProgram)) return str(programs) programs = tempprograms[:] intProgram = -1 nextprogram(None) return str(programs)
def getNVDAVolume(): try: sessions = AudioUtilities.GetAllSessions() except: # noqa:E722 # no supported log.warning( "AudioUtilities getAllCessions not supported on this system") return False for session in sessions: try: name = session.Process.name() except: # noqa:E722 continue if name.lower() == "nvda.exe": volume = session.SimpleAudioVolume volumeLevel = volume.GetMasterVolume() return volumeLevel return None
def main(): song = AudioSegment.from_mp3("beep.mp3") global sess, vol play(song) sessions = AudioUtilities.GetAllSessions() for session in sessions: # if session.Process: # print(session.Process.name()) if session.Process and session.Process.name() == "python.exe": sess = session vol = sess._ctl.QueryInterface(ISimpleAudioVolume) print("volume.GetMasterVolume(): %s" % vol.GetMasterVolume()) vol.SetMasterVolume(0, None) play(song) vol.SetMasterVolume(1, None) play(song)
def AudioSessions(): global OPEN_SESSIONS, SESSION_NAMES, SESSIONS_CHANGED_FLAG, SESSION_CHECKED_TIME, SESSION_PIDS_GLOBAL current_sessions = AudioUtilities.GetAllSessions( ) # Gets a list of all current audio session objects cleaned_sessions = [] session_pids = [] for session in current_sessions: if (session.Process != None): cleaned_sessions.append(session) session_pids.append(session.Process.pid) else: None if session_pids != SESSION_PIDS_GLOBAL: # Will only change things if it is different to what is already there SESSIONS_CHANGED_FLAG = True SESSION_PIDS_GLOBAL = session_pids OPEN_SESSIONS.clear() SESSION_NAMES.clear() for session in cleaned_sessions: # Steps through the audio sessions name = session.Process.name() # Reads name of session name = name[0:-4] # Takes the .exe off the name name = name[:16] # Ensures the name is not too long for the screen OPEN_SESSIONS.append( session.SimpleAudioVolume ) # List of the session objects, these are what are used to change the volume SESSION_NAMES.append( name.capitalize()) # List of the session names, capitalized SESSION_CHECKED_TIME = time.time() return None
def request_blood(): #pause the on going bhajans and make the announcement and unpause the song if request.method=='POST': result = request.form #stop_thread(bhajans_play) global flag flag=0 print result == {} if result == {}: blood_group_list = ['O+','O-','A+','A-','B-','B+','AB-','AB+','ALL'] return render_template('home.html',blood_group_list=blood_group_list) pause() flag=1 devices = AudioUtilities.GetSpeakers() interface = devices.Activate( IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) volume.GetMute() volume.GetMasterVolumeLevel() volume.GetVolumeRange() volume.SetMasterVolumeLevel(-10.0, None) play_audio('audio/1.wav') time.sleep(1) for times in range(1,3): print "Result" print result if 'ALL' in result: play_all_blood_audio() else: play_individual_blood_audio(result) if times%2==1: # for 'I repeat' play_audio('audio/8.wav') #play_audio('') #play_audio('') time.sleep(0.5) play_audio('audio/9.wav') volume.SetMasterVolumeLevel(-20.0, None) unpause() return render_template('after_announ.html')
def __init__(self): "find all the sound devices" try: from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume sessions = AudioUtilities.GetAllSessions() self.volumes = [ session._ctl.QueryInterface(ISimpleAudioVolume) for session in sessions ] # is already muted? self.origMute = [v.GetMute() for v in self.volumes] #except ImportError: # 20180409 -- if it fails for anyreason, continue except: # set no volumes and no origMutes, nothing will be done by funcs below if os.name in ['nt']: print("WARNING: no volume control; install pycaw") print( "\tpython -m pip --user install https://github.com/AndreMiras/pycaw/archive/master.zip" ) self.volumes = [] self.origMute = []
def cycleThroughApps(self, goForward): audioSessions = AudioUtilities.GetAllSessions() sessions = [] sessions.append(self.master_volume) for session in audioSessions: if session.Process is not None: sessions.append(session) newSession = None idx = 0 nrSessions = len(sessions) while idx < nrSessions: session = sessions[idx] if self.curAppName == session.Process.name(): if goForward: newSession = sessions[idx + 1] if idx + 1 < nrSessions else sessions[0] else: newSession = sessions[idx - 1] idx += 1 if newSession is None: newSession = sessions[0] self.curAppName = newSession.Process.name() if newSession.Process is not None else newSession.name self.message(SM_CTX_APP_CHANGE, self.getAppNameFromSession(newSession))
def script_turn(self, gesture): self.enabled = not self.enabled if not self.enabled: tones.beep(440, 100) self.set_standard_gestures() return all_sessions = AudioUtilities.GetAllSessions() self.apps = [] del self.app_index self.apps.append(self.master_volume) for session in all_sessions: if session.Process: s = session.SimpleAudioVolume s.name = session.Process.name() self.apps.append(s) if s.name == self.current_app.name: self.app_index = len(self.apps) - 1 if not hasattr(self, 'app_index'): self.app_index = 0 self.current_app = self.apps[self.app_index] tones.beep(660, 100) self.set_all_gestures()
def main(): try: app_to_mute = sys.argv[1] except IndexError: app_to_mute = "Discord.exe" # setup volume volume = None vol = None sessions = AudioUtilities.GetAllSessions() for session in sessions: if session.Process and session.Process.name() == app_to_mute: volume = session._ctl.QueryInterface(ISimpleAudioVolume) vol = volume.GetMasterVolume() # vars try: memory = gd.memory.get_memory() except RuntimeError: print("Open GD before running!") time.sleep(5) exit() muted = False gettingfar = input("what percent to mute at?: ") # mainloop while True: memory.reload() percent = memory.get_percent() if percent == int(gettingfar): if not muted: volume.SetMasterVolume(0, None) muted = True if memory.is_dead(): if muted: volume.SetMasterVolume(vol, None) muted = False time.sleep(0.5)
def system_volume(self, vol): try: if vol: devices = AudioUtilities.GetSpeakers() interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) self.volume = cast(interface, POINTER(IAudioEndpointVolume)) current_volume_level = self.volume.GetMasterVolumeLevel() if "+" in vol: value = int(vol.replace("+", "")) * -3 value = float(current_volume_level + value) elif "-" in vol: value = int(vol.replace("-", "")) * -3 value = float(current_volume_level - value) elif vol.isdigit(): percentage = int(vol) / 100 value = (-30 - (-30 * percentage)) # ensure value in range if value > 0.0: value = 0.0 # 0% elif value < -30.0: value = -30.0 # 100% # volume.GetMute() # volume.GetVolumeRange() # volume range: # max: 0.0 # min: -65.25 self.volume.SetMasterVolumeLevel(value, None) return str(((self.volume.GetMasterVolumeLevel() / -30) * 100)) except Exception as ex: raise Exception( f"SYSTEM VOLUME LIBRARY Encountered an Error. {str(ex)}")
def updateVolume(self, volume): ''' Function to change the volume in a lerp fassion (basiclly smoothly) still a bit weird ''' sessions = AudioUtilities.GetAllSessions() for session in sessions: ''' One issue that can occur is having multiple browsers open, the app will pick the first browser that windows media player returns ''' if session.Process and session.Process.name().lower() in self.applications: spotify = session.SimpleAudioVolume if self.Volume > volume: for x in range(1, 10): spotify.SetMasterVolume(volume + abs(volume - self.Volume)/x, None) sleep(0.2) else: for x in range(1, 10): spotify.SetMasterVolume( volume - abs(volume - self.Volume)/x, None) sleep(0.2) self.Volume = volume
def main(): # Thanks to WoolDoughnut310 for the values: https://github.com/AndreMiras/pycaw/issues/13#issuecomment453862389 volumes = [64, 56.9, 51.6, 47.7, 44.6, 42, 39.8, 37.8, 36.1, 34.6, 33.2, 31.9, 30.7, 29.6, 28.6, 27.7, 26.8, 25.9, 25.1, 24.3, 23.6, 22.9, 22.2, 21.6, 21, 20.4, 19.8, 19.3, 18.8, 18.3, 17.8, 17.3, 16.8, 16.4, 16, 15.5, 15.1, 14.7, 14.3, 13.9, 13.6, 13.2, 12.9, 12.5, 12.2, 11.8, 11.5, 11.2, 10.9, 10.6, 10.3, 10, 9.7, 9.4, 9.1, 8.9, 8.6, 8.3, 8.1, 7.8, 7.6, 7.3, 7.1, 6.9, 6.6, 6.4, 6.2, 5.9, 5.7, 5.5, 5.3, 5.1, 4.9, 4.7, 4.5, 4.3, 4.1, 3.9, 3.7, 3.5, 3.3, 3.1, 2.9, 2.7, 2.6, 2.4, 2.2, 2, 1.9, 1.7, 1.5, 1.4, 1.2, 1, 0.9, 0.7, 0.6, 0.4, 0.3, 0.1, 0] try: while True: time.sleep(1) devices = AudioUtilities.GetSpeakers() interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) if (volume.GetMute() != 1): currentVolume = abs(round(volume.GetMasterVolumeLevel(), 1)) nearest = 0 for i in range(1, 100): near = abs(currentVolume - volumes[i]) if (near < abs(currentVolume - volumes[nearest])): nearest = i nearest = int(round(nearest / 5) * 5) volume.SetMasterVolumeLevel(volumes[nearest] * -1, None) except: # On connection timeout time.sleep(1) return main()
async def volume_change(self, target_volume, over_seconds=None, step_time=0.1): print(target_volume) sessions = AudioUtilities.GetAllSessions() for session in sessions: volume = session._ctl.QueryInterface(ISimpleAudioVolume) current_volume_level = volume.GetMasterVolume() if session.Process and 'discord' not in session.Process.name().lower(): if over_seconds is not None: step_count = over_seconds / step_time if target_volume < current_volume_level: volume_step_size = (current_volume_level - target_volume) / step_count else: volume_step_size = (target_volume - current_volume_level) / step_count for _ in range(int(step_count)): if target_volume > current_volume_level: current_volume_level = current_volume_level + volume_step_size else: current_volume_level = current_volume_level - volume_step_size await asyncio.sleep(step_time) print(f'{current_volume_level}') volume.SetMasterVolume(current_volume_level, None) else: volume.SetMasterVolume(target_volume, None)
def main(): vol = volDB = 0 pTime = cTime = 0 timeDuration = time.time() Running = True cap = cv.VideoCapture(0) dectector = htm.handDetector(detectionCon=0.3) devices = AudioUtilities.GetSpeakers() interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) winVolume = volume.GetMasterVolumeLevel() while Running: success, img = cap.read() img = dectector.findHands(img) finger_xy = dectector.findPosition(img) if finger_xy: if (time.time() - timeDuration) > 0.5: volDB = htm.volumeWIN[int(vol)] vol = gestureSliderNum(finger_xy) timeDuration = time.time() # drawSlider(vol, img) cv.rectangle(img, (600, 340), (620, 440), (177, 132, 91), 2) cv.rectangle(img, (600, 440 - int(vol)), (620, 440), (106, 118, 252), -1) cv.putText(img, 'Vol: ' + str(int(vol)) + '%', (555, 460), cv.FONT_HERSHEY_PLAIN, 1, (0, 0, 0), 1) volume.SetMasterVolumeLevel(volDB, None) cTime = time.time() fps = 1 / (cTime - pTime) pTime = cTime cv.putText(img, 'FPS: ' + str(int(fps)), (5, 15), cv.FONT_HERSHEY_PLAIN, 1, (0, 0, 0), 2) cv.imshow("Image", img) if cv.waitKey(1) & 0xFF == ord('q'): Running = False cv.destroyAllWindows() volume.SetMasterVolumeLevel(winVolume, None)
def toggleProcessVolume(processName): """ Mutes or unmute process volume """ try: sessions = AudioUtilities.GetAllSessions() except: # noqa:E722 # no supported log.warning( "AudioUtilities getAllCessions not supported on this system") return for session in sessions: try: name = session.Process.name() except: # noqa:E722 continue if name == processName: volume = session.SimpleAudioVolume mute = volume.GetMute() volume.SetMute(not mute, None) if not volume.GetMute(): ui.message(_("Volume on")) else: ui.message(_("volume off")) return ui.message(_("No audio controller for this application"))
import HandTrackingModule as htm from ctypes import cast, POINTER from comtypes import CLSCTX_ALL from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume ############################################## wCam, hCam = 640, 480 ############################################## cap = cv2.VideoCapture(0) cap.set(3, wCam) cap.set(4, hCam) pTime = 0 detector = htm.handDetector(detectionCon=0.7) devices = AudioUtilities.GetSpeakers() interface = devices.Activate( IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) volume.GetMute() volume.GetMasterVolumeLevel() volRange = volume.GetVolumeRange() minVolume = volRange[0] maxVolume = volRange[1] print(volRange) vol = 0 volbar = 400 volper = 0 while (True): success, img = cap.read()
def __init__(self): self.devices = AudioUtilities.GetSpeakers() self.interface = self.devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) self.volume = cast(self.interface, POINTER(IAudioEndpointVolume))
def volumedown(): devices = AudioUtilities.GetSpeakers() interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) volume.SetMasterVolumeLevel(volume.GetVolumeRange()[0], None)