Revised Answer:
arecord
needs an environment variable called XDG_RUNTIME_DIR
to locate the resources it needs. By default our cron
jobs run in a different environment than (for example) the one in our interactive shell, and the cron
environment won't (by default) include the variable XDG_RUNTIME_DIR
.
The solution then is to add this environment variable in your crontab
. Once cron
has this environment variable, it should run it with no complaints. Here's how to do this:
- Open your
crontab
for editing:
$ crontab -e
- With your
crontab
open in the editor, add the following line above the line you use to start arecord
:
XDG_RUNTIME_DIR=/run/user/1000
I've used 1000
as the uid
here as that is default for user pi
in RPi OS. You can verify this by entering id pi
a the command line.
For future reference:
The environment in cron
is austere, at least in part, to reduce the risk of potential security issues. Sometimes, we need to know just exactly what the cron
environment is... How do we do that? The easiest and best way I've found to do this is to ask cron
to tell us! We add the printenv
command in our crontab
, and redirect it to a file in our home directory:
@reboot /bin/sleep; /usr/bin/printenv > /home/pi/mycronenv.txt 2>&1
This will give you a handy reference file containing your cron
environment, updated each time you reboot
. You can compare it against the printenv
output from your interactive shell the next time your cron
job misfires :)
Original Answer:
Try using /usr/bin/arecord
instead of arecord
in your crontab
entry.
cron
runs in a different environment than the one you have in your interactive shell. It doesn't know where arecord
is - so you must tell it.
I don't know enough about arecord
to understand the effect of specifying the "hardware option", but try this first & we'll go from there.
EDIT:
According to this Ubuntu Q&A, there is an environment variable associated with the use of arecord
(XDG_RUNTIME_DIR), and it is dependent on the userid
.
This answer doesn't explain things extremely well, but there is another answer that seems to do a better job of explanation..
Your difficulty here is due to the fact that cron
does not have the same environment as you do from your interactive shell, and it does not have the same environment as you do in your windowing/X environment. And so, the solution must be to provide cron
the environment variable that contains your hardware information.
I can't try this on my machine because: a) it is RPi Lite (no desktop/windows), and b) no microphone. Therefore, I will only suggest that you try adding the following line to your crontab
file somewhere above the line you invoke arecord
:
XDG_RUNTIME_DIR=/run/user/1000
Note: I assume user pi & UID = 1000
Please also note that this was adapted from the Ubuntu example, and while the approach may be good, things may be arranged differently in RPi OS - IOW, you may have to tweak this some :)