拔掉耳机就静音?

Dan*_*man 13 sound headphones speakers audio-jack

每次我拔下耳机(就像手机一样)以停止声音然后从我的扬声器播放时,有没有办法让我的电脑静音?

con*_*use 11

如何检测拔掉插头

基本上对我有用的是:

# When plugged in:
cat /proc/asound/card0/codec#0 > pluggedin.txt

# When not plugged in:
cat /proc/asound/card0/codec#0 > notplugged.txt

# Then compare the differences
diff pluggedin.txt notplugged.txt
Run Code Online (Sandbox Code Playgroud)

对我来说,不同之处在于“Amp-Out vals”下的“Node 0x16”:

Node 0x16 [Pin Complex] wcaps 0x40058d: Stereo Amp-Out             Node 0x16 [PinComplex] wcaps 0x40058d: Stereo Amp-Out
  Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1         Amp-Out caps:ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1
  Amp-Out vals:  [0x80 0x80]                                    |    Amp-Out vals:  [0x00 0x00]
Run Code Online (Sandbox Code Playgroud)

所以我基于发现的差异进行检测。

如何静音

有了这些知识,您就可以在后台运行一个脚本。如果拔下插头,脚本会像使用amixer sset Master playback 0%(或任何其他命令)一样使您的扬声器静音。

#!/bin/bash
# This scripts detecs unplugging headphones.

oldstatus="unrelated string"
while [ 1 ]; do
    # The following line has to be changed depending on the difference (use diff) in '/proc/asound/card0/code#0'
    status=$(grep -A 4 'Node 0x16' '/proc/asound/card0/codec#0' |  grep 'Amp-Out vals:  \[0x80 0x80\]')
    if [ "$status" != "$oldstatus" ]; then
        if [ -n "$status" ]; then
            echo "Plugged in"
             amixer sset Master playback 80% # Set volume to 80%
            oldstatus="$status"
        else
            echo "Unplugged"
            amixer sset Master playback 0%  # Mute
            oldstatus="$status"
        fi
    fi
done
Run Code Online (Sandbox Code Playgroud)

您可以使其可执行chmod +x scriptname.sh并将其放入启动应用程序中。您将不得不通过找到自己的差异来调整拔出检测/proc/asound/card0/codec#0(甚至可能在这里更改多个声卡的数字。

相关链接:

https://wiki.ubuntu.com/Audio/PreciseJackDetectionTesting

https://unix.stackexchange.com/questions/25776/detecting-headphone-connection-disconnection-in-linux

拔出/插入耳机时如何自动更改音量?

  • 在后台连续运行带有无限`while` 循环(甚至没有一点睡眠指令)的脚本远非理想的解决方案;除了是 CPU 和电池杀手之外,这是一个丑陋和 hacky 的解决方法。我试了一下,从正常的 5% 的 CPU 使用率(浏览器、spotify、终端、IDE、Telegram 和其他应用程序打开)到 45% 的 CPU 使用率。 (5认同)