编写这样的脚本相当简单——您需要通过管道acpi_listen连接到while IFS= read -r line ; do ... done结构,并处理该结构中的事件。shell 内置命令将read等待一行文本,acpi_listen当if语句看到该行包含适当的文本时,将进行处理。或者,可以使用case语句来提高脚本的可移植性。
这是我个人会使用的简单脚本。在 Ubuntu 16.04 LTS 上测试
#!/bin/bash
acpi_listen | while IFS= read -r line;
do
if [ "$line" = "jack/headphone HEADPHONE plug" ]
then
notify-send "headphones connected"
sleep 1.5 && killall notify-osd
elif [ "$line" = "jack/headphone HEADPHONE unplug" ]
then
notify-send "headphones disconnected"
sleep 1.5 && killall notify-osd
fi
done
# Play/pause music like in smartphones
# Play when the headphone was plugged in,
# pause when the headphone was unplugged
# As there is no separate option in Audacious
# for playing even if it is already playing
# (or for pausing even if it is already paused),
# only toggles (e.g. play when paused, otherwise pause),
# I was forced to check the state of playback
# from PulseAudio (using `pacmd`).
# Added control for vlc (src: https://stackoverflow.com/a/43156436/3408342)
#!/bin/bash
acpi_listen | while IFS= read -r line; do
test=$(pacmd list-sink-inputs | grep "application.process.binary\|state" | \sed 's/[="]//g' - | awk '{print $2}')
if [[ $test ]]; then
stateAud=$(echo "$test" | grep audacious -B1 | head -1)
stateVlc=$(echo "$test" | grep vlc -B1 | head -1)
# Play music when headphone jack has been plugged in AND the stateAud is corked/paused
if [[ "$line" = "jack/headphone HEADPHONE plug" && $stateAud = "CORKED" ]]; then
audacious -t
fi
if [[ "$line" = "jack/headphone HEADPHONE plug" && $stateVlc = "CORKED" ]]; then
dbus-send --type=method_call --dest=org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Play
fi
if [[ "$line" = "jack/headphone HEADPHONE unplug" && $stateAud = "RUNNING" ]]; then
audacious -t
fi
if [[ "$line" = "jack/headphone HEADPHONE unplug" && $stateVlc = "RUNNING" ]]; then
dbus-send --type=method_call --dest=org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Pause
fi
echo
fi
done
编写这样的脚本相当简单——您需要通过管道
acpi_listen
连接到while IFS= read -r line ; do ... done
结构,并处理该结构中的事件。shell 内置命令将read
等待一行文本,acpi_listen
当if
语句看到该行包含适当的文本时,将进行处理。或者,可以使用case
语句来提高脚本的可移植性。这是我个人会使用的简单脚本。在 Ubuntu 16.04 LTS 上测试
请注意,如果您计划从 cron 作业或通过 运行此操作,则
/etc/rc.local
需要导出您的DBUS_SESSION_BUS_ADDRESS
fornotify-send
才能工作。我一直在寻找类似的东西,但不是通知,而是我想在拔掉电源时暂停(并且正在播放音乐)并在插入时播放(并且音乐被暂停)。
我知道,这并不是OP 所要求的,但我不能在这里发表评论(可惜 Stack Exchange 站点没有相互累积声誉分数)。
无论如何,这是@Sergiy 的修改后的脚本。我不是说它是优化的或其他什么,但它正在工作。如果有人(Basher Pro?;p)会改进它,我会很高兴。:)
顺便说一句,我尝试将它与vlc
(或cvlc
,nvlc
)一起使用,但我找不到vlc
在后台运行时从终端切换播放/暂停的方法(我一直在做的事情)。请注意,我使用
audacious
播放器——如果您使用其他任何东西,您需要更改$state
变量和播放/暂停命令。更新 增加了对 vlc 的控制(基于这个答案,正如@BenjaminR 指出的那样)。