bashcroncron-taskzenity

playing sound file when bash script is ran by cron task


below is a bash script that works fine tested in my terminal the sound is played but when it is actually ran in a cron scheduled task there is no sound only the dialog is shown

#!/bin/bash

export DISPLAY=:0
export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus

SOUND_FILE="/home/k1dlinux/sounds/alarm01.wav"

# looping sound
(
    while true; do
        paplay "$SOUND_FILE"
        sleep 0.5
    done
) &

SOUND_PID=$!

# info dialog
zenity --info \
    --title="⏰ ALARM - 11:00 AM" \
    --text="<big><b>Daily Alarm Reminder</b></big>\n\nIt's 11:00 AM - Time for your scheduled task!\n\nClick OK to dismiss." \
    --width=400 \
    --height=200 \
    --ok-label="Dismiss Alarm"

# stop sound
kill $SOUND_PID 2>/dev/null
pkill -P $SOUND_PID 2>/dev/null

Solution

  • The issue is that PulseAudio requires additional environment variables that aren't set in cron's minimal environment. While you've correctly set DISPLAY and DBUS_SESSION_BUS_ADDRESS for the GUI (which is why zenity works), paplay needs to connect to your PulseAudio server.

    Solution

    Add these environment variables at the top of your script:

    bash

    #!/bin/bash
    
    export DISPLAY=:0
    export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus
    
    # Add PulseAudio environment variables
    export XDG_RUNTIME_DIR="/run/user/$(id -u)"
    export PULSE_RUNTIME_PATH="/run/user/$(id -u)/pulse"
    
    SOUND_FILE="/home/k1dlinux/sounds/alarm01.wav"
    
    # looping sound
    (
        while true; do
            paplay "$SOUND_FILE"
            sleep 0.5
        done
    ) &
    
    SOUND_PID=$!
    
    # info dialog
    zenity --info \
        --title="⏰ ALARM - 11:00 AM" \
        --text="<big><b>Daily Alarm Reminder</b></big>\n\nIt's 11:00 AM - Time for your scheduled task!\n\nClick OK to dismiss." \
        --width=400 \
        --height=200 \
        --ok-label="Dismiss Alarm"
    
    # stop sound
    kill $SOUND_PID 2>/dev/null
    pkill -P $SOUND_PID 2>/dev/null