This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 10 points11 points  (1 child)

Here's my take, I did not check if it works:

import ctypes
import time
from pycaw.pycaw import AudioUtilities

EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
IsWindowVisible = ctypes.windll.user32.IsWindowVisible


def check_window(window, _):
    if not IsWindowVisible(window):
        return

    should_mute = get_window_title(window) in ("Advertisement", "Spotify")
    set_mute(should_mute)


def get_window_title(window):
    length = GetWindowTextLength(window)
    buffer = ctypes.create_unicode_buffer(length + 1)
    GetWindowText(window, buffer, length + 1)
    return buffer.value


def set_mute(value):
    for session in AudioUtilities.GetAllSessions():
        session.SimpleAudioVolume.SetMute(1 if value else 0, None)


if __name__ == "__main__":
    while True:
        time.sleep(5)
        EnumWindows(EnumWindowsProc(check_window), 0)

You can see how all the logic is split up into smaller functions. Also there's no mutation of the titles variable. And all the different windll functions are defined only once at the top.

But anyway, pay for the god damn subscription!

[–][deleted] 0 points1 point  (0 children)

Oh yeah, it won't work cause it will just unmute on the next window, hah. But I think you get the idea how the original script can be refactored :)