I am writing a python script which utilizes a Raspberry PI's GPIO and thus the script must be elevated to run as sudo in order to obtain correct privileges for /dev/mem and /dev/gpiomem and access the GPIO.
However I want to play sounds from this script too, so I am now using
os.system(cmd) method which allows Python to execute shell commands.
I am using this method to load wav files to aplay.
defaultUser = 'pi' #the user to run the command as cmd = 'sudo -H -u %s bash -c \'aplay sounds/%s &\'' % (defaultUser, filename) os.system(cmd) #now run the command as if it were typed into the shell
The above attempts to launch the command as the default user, and this used to work fine back when I was using alsa by it's self. however due to popping/crackling noise of the DACs turning on and off I had to switch to pulse audio and disable module-suspend-on-idle.
This lead to the above issue where I am no longer able to producing sound at all from root user.
I have tried executing these commands in the shell in an attempt to launch aplay as the default user (but none actually play any sound):
$ sudo -H -u pi bash -c 'aplay sounds/beep.wav &' $ Playing WAVE 'sounds/3tone.wav' : Signed 16 bit Little Endian, Rate 44100 Hz, Mono
$ sudo -u pi aplay sounds/beep.wav $ Playing WAVE 'sounds/beep.wav' : Signed 16 bit Little Endian, Rate 44100 Hz, Mono
Both of which produce good verbose output, just no audio.
And I do get audio if I run as non-root user (aka. pi)
What could cause pulseaudio or aplay to work for non-root user, but not when root initiates a command to run as default user?
This has trapped me in a catch 22 where I need sudo but sudo causes issues.
Thanks for any guidance!