Submitted by Mike on Sun, 05/24/2015 - 7:11am
Want to play audio on your Raspberry Pi running Raspbian, while logged in to a non-root user account? Me, too!
Seems like such a simple task.
Consider the following code snippet using PyGame:
import time
import pygame
pygame.mixer.init()
pygame.mixer.music.load("testfile.wav")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
time.sleep(.25)
Let's try it:
$ python soundtest.py
Traceback (most recent call last):
File "./soundtest.py", line 3, in <module>
pygame.mixer.init()
pygame.error: No available audio device
But, if you run the script using sudo, it plays as expected.
The solution? Add non-root users to the `audio` group [1] in order to play audio.
$ sudo usermod -a -G audio <username>
Important: Log out of the user account, then log in again in order to force the new group membership to take effect.
[1] http://raspberrypi.stackexchange.com/a/3640