我在 UBuntu 16.04 上。我问了一个问题这里关于耳机插拔事件。我试过的办法没有奏效。我想使用acpi_listen命令监听耳机连接事件并使用通知发送显示消息。如何在shell 脚本?
答案1
编写这样的脚本相当简单 - 您需要通过管道传输acpi_listen
到while IFS= read -r line ; do ... done
结构,并负责处理该结构内的事件。shellread
内置命令将等待一行文本,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
请注意,如果您计划从 cron job 或 via 运行此程序/etc/rc.local
,则需要导出您的DBUS_SESSION_BUS_ADDRESS
fornotify-send
才能工作。
答案2
我正在寻找类似的东西,但不是通知,而是想在拔下电源时暂停(并且音乐正在播放),并在插入电源时播放(并且音乐暂停)。
我知道,这不是确切地原始发帖人要求的,但我无法在此发表评论(遗憾的是 Stack Exchange 网站不互相积累声誉分数)。
无论如何,这是@Sergiy 的修改后的脚本。我并不是说它经过了优化或其他什么,但它确实有效。如果有人(Basher Pro?;p)能改进它,我会很高兴。:)
顺便说一句,我尝试将它与vlc
(或cvlc
,nvlc
)一起使用,但我找不到在vlc
后台运行时从终端切换播放/暂停的方法(我一直在这样做)。
请注意,我使用的是audacious
播放器——如果您使用其他播放器,则需要更改$state
变量和播放/暂停命令。
更新 增加了对 vlc 的控制(基于这答案,正如@BenjaminR 指出的那样)。
# 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