crontab 运行自定义脚本时没有声音

crontab 运行自定义脚本时没有声音
#! /bin/bash

# Read battery percentage value
OUT=`upower -i /org/freedesktop/UPower/devices/battery_BAT1 | grep percentage`

# Select only the int value
IFS=':' read -ra P <<< "$OUT"
PERCENTAGE="%"
BATTERY_VALUE=${P[1]%$PERCENTAGE}

# Send a notification if battery level is under 15% and not on AC power
if ! on_ac_power; then
  if (($BATTERY_VALUE  < "15")); then
      eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)";
      notify-send -u critical -i "battery-caution" "Battery low! You should plug in your laptop!"
      /usr/bin/aplay /usr/share/sounds/desktop-logout.oga
  fi
fi

# Send a notification if battery level is equal to or over 90% and is on AC power
if on_ac_power; then
  if (($BATTERY_VALUE  >= "90")); then
      eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)";
      notify-send -u critical -i "battery-full-charging" "Battery charged! You should unplug your laptop!"
      /usr/bin/aplay /usr/share/sounds/desktop-logout.oga
  fi
fi

如果我手动执行脚本,声音和脚本工作正常。我收到来自notify-send的通知,但它没有播放来自crontab的声音。Cron日志显示:

Connection failure: Connection refused
pa_context_connect() failed: Connection refused. 

我尝试过该命令paplay并指向 paplay 的绝对路径但/usr/bin/paplay无济于事。

答案1

我发现,当我应该在命令行中使用 pulseaudio 向另一个用户发送声音时,应该指示环境变量:

XDG_RUNTIME_DIR="/run/user/usr_id"

将“usr_id”替换为与用户对应的 id(数字)(这里如何获得外部您可以使用 crontab 命令来管理 crontab。

计划任务示例:

* * * * * XDG_RUNTIME_DIR=/run/user/$(id -u) /path/to/script

它将自动使用当前用户ID。

问题看起来是 crontab 的环境非常有限。

来源ArchLinux Wiki:PulseAudio

相关内容