Pulseaudio, MPD and systemd

I recently had a problem with MPD and pulseaudio, on my Fedora station, and I struggled for a long time before I could find a solution, so now I’m writing the blog post that I would have loved to find yesterday. Just in case someone has the same issue.

I want all my applications to go through pulseaudio, to have a smooth audio experience. For things like mpv, firefox, teeworlds, etc that’s easy, they run as my own user, so they spawn pulseaudio the first time one of them wants to play sound, or they use the existing pulseaudio instance if it is already running. Easy.

The problem with MPD is that it’s supposed to be a system daemon. If you run that daemon as its own user (mpd), it will spawn its own pulseaudio process, and it will clash with your user’s one (they can’t play sound at the same time, in my experience).

To circumvent this problem, I configured mpd to run as my own user (using the option user "louiz"), but I encountered this issue:

Aug 15 01:34:35 abricot pulseaudio[6521]: [pulseaudio] socket-server.c: bind(): Address already in use
Aug 15 01:34:35 abricot pulseaudio[6521]: [pulseaudio] main.c: Failed to initialize daemon.
Aug 15 01:34:35 abricot pulseaudio[6518]: [pulseaudio] main.c: Daemon startup failed.
Aug 15 01:34:35 abricot mpd[6244]: pulse_output: Failed to enable "My Pulse Output" [pulse]: pa_context_connect() has failed: Connection refused

(You can see that in the logs of the mpd.service daemon, using journalctl -u mpd.service).

MPD apparently tries to spawn a new pulseaudio process, as my own user, and it fails because it is already running. I could not understand why it could not just use the existing pulseaudio instance, without trying to spawn a new one.

I understood thanks to this post (after hours of digging, I even asked on #pulseaudio@irc.freenode.org, to no avail).

MPD could not find the already-running pulseaudio instance because the environment variable XDG_RUNTIME_DIR was not set, and that’s where pulseaudio stores its files (the socket, the process pid, etc).

To fix the problem (that may not be the smartest solution, if you know a better one, please let me know), I customized the systemd unit for the MPD service by creating a new file /etc/systemd/system/mpd.service.d/fixenv.conf containing:

[Service]
Environment=XDG_RUNTIME_DIR=/run/user/1000

Of course, replace 1000 by the UNIX id of your user.

With this additional environment variable, when mpd wants to play sound using pulseaudio, it directly finds the existing pulseaudio instance and starts playing sound immediately.