如何在未聚焦时自动静音应用程序?

Bat*_*TAG 3 sound scripts steam games

当我玩一些像骑士中世纪战争这样的游戏并且我切换到另一个软件像火狐或桌面时,游戏的声音仍然在播放。

那么,我该如何解决这个问题?

Jac*_*ijm 5

(自动)将特定应用程序的声音静音(如果其窗口不在前面)

我在 Rhythmbox 上测试了下面的脚本,没有出现任何错误。

如果目标进程的窗口不在前面(一秒内),则在后台运行下面的脚本将暂停目标进程,如果应用程序附带它,则将声音静音。
每当窗口再次出现在前面时,该过程就会恢复到原来的位置,并且声音再次起作用。

如果目标进程/应用程序根本没有运行,脚本将切换到更长的周期(模式),每五秒只检查一次目标应用程序是否运行。这样,如果脚本没有工作要完成,它的汁液就会非常少。

剧本

#!/usr/bin/env python3
import subprocess
import time

# ---set the proc to pause when not the active window
wclass = "rhythmbox"
# ---

def get(cmd):
    # just a helper function to not repeat verbose subprocess sections
    try:
        return subprocess.check_output(cmd).decode("utf-8").strip()
    except subprocess.CalledProcessError:
        pass

while True:
    # the longer period: application is not running (saving fuel)
    time.sleep(5)
    front1 = ""
    while True:
        # if the application runs, switch to a shorter response time
        time.sleep(1)
        # get the possible pid, get() returns "None" if not running,
        # script then switches back to 5 sec check
        pid = get(["pgrep", wclass])
        if pid:
            front2 = wclass in get([
                "xprop", "-id", get(["xdotool", "getactivewindow"])
                ])
            # run either kill -stop or kill -cont only if there is
            # a change in the situation
            if front2 != front1:
                if front2 == True:
                    cm = ["kill", "-cont", pid]
                    print("run") # just a test indicator, remove afterwards
                else:
                    cm = ["kill", "-stop", pid]
                    print("stop") # just a test indicator, remove afterwards
                subprocess.Popen(cm)
            front1 = front2
        else:
            break
Run Code Online (Sandbox Code Playgroud)

如何使用

笔记

该脚本可以轻松编辑以针对多个应用程序,但首先请查看这是否是您需要的。

或者

如果您希望在目标窗口不在前面时通常将声音静音,请将暂停应用程序的命令替换为静音 (/unmute) sound的命令。然后脚本变成:

sudo apt-get install xdotool
Run Code Online (Sandbox Code Playgroud)

用法与第一个脚本完全相似。