Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Audio doesn't play with crontab on Raspberry Pi

I'm trying to get my Raspberry Pi which is currently connect to a bluetooth speaker to play an audio file daily on a schedule basis where my cron job is being update @daily to get new timing (It's basically a call to prayer)

crontab -l

@daily /home/pi/athan/update_prayers.sh
39 05 27 2 * /home/pi/athan/call_prayer.sh >/dev/null 2>&1 #fajr
31 12 27 2 * /home/pi/athan/call_prayer.sh >/dev/null 2>&1 #dhuhr
34 15 27 2 * /home/pi/athan/call_prayer.sh >/dev/null 2>&1 #asr
05 18 27 2 * /home/pi/athan/call_prayer.sh >/dev/null 2>&1 #maghrib
24 19 27 2 * /home/pi/athan/call_prayer.sh >/dev/null 2>&1 #isha

So, the above is what I have right now and this is the content of /home/pi/athan/update_prayers.sh

#!/bin/bash
/home/pi/.nvm/versions/node/v7.5.0/bin/node /home/pi/athan/set_prayer.js

Basically my set_prayer.js is just using this https://www.npmjs.com/package/crontab module to set crontab and I was able to get it update daily no problem here. Right now I'm using Mplayer to play the audio and this is the command I use:

/home/pi/athan/call_prayer.sh

#!/bin/bash
/usr/bin/mplayer /home/pi/athan/athan.mp3

My problem here is that when it's time for the cron job to run there's no sound or I don't even know if the job is being run, but when I do it manually I can hear the audio being played no problem. I've also tried to run it directly here using /usr/bin/omxplayer -o alsa /home/pi/athan/athan.mp3 instead of running bash script and it doesn't seem to work with cron but works fine when I run the command directly.

like image 302
Ali Avatar asked Dec 01 '22 15:12

Ali


1 Answers

I was struggling with a similar problem (no audio on Bluetooth speaker if the command is run from crontab.

The problem was the mix pulseaudio/crontab and the environment setup.

The following solution worked for me: https://wiki.archlinux.org/index.php/PulseAudio#Play_sound_from_a_non-interactive_shell_.28systemd_service.2C_cron.29

so basically just do crontab -e and add the following:

XDG_RUNTIME_DIR=/run/user/user_id

the user id can be found out by the following command:

id [user_name]

You can also use this in crontab:

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

it will automatically use current user ID.

like image 99
Yacine Avatar answered Dec 06 '22 07:12

Yacine