Score:0

How to connect to pulseaudio server from service

in flag

I'm developing a simple app to duck audio automatically using the pulsectl-asyncio library. I've developed the application in Python with a virtual environment, and when I run the script from the command-line, it works fine: /path/to/venv/bin/python /path/to/main.py.

The problem is running it as a service. When I run the script as a service, I get an error: pulsectl.pulsectl.PulseError: Failed to connect to pulseaudio server. The following is my service configuration:

[Unit]
Description=Auto-ducker
After=multi-user.target
[Service]
Type=simple
Restart=always
User=myuser
Group=myuser
ExecStart=/path/to/venv/bin/python /path/to/main.py
[Install]
WantedBy=multi-user.target

I get the same error when I run the script as myself through sudo: sudo -H -u myuser bash -c '/path/to/venv/bin/python /path/to/main.py'.

Why does the script run from the command-line but not as a service? And how can I run the script as a service?

Matias N Goldberg avatar
vg flag
Most PulseAudio apps need a working xorg session environment (or Wayland, + dbus, etc). This is sent through environment variables. I don't know if it's possible, but if so, you need to tell systemd to inherit the necessary env variables from myuser's graphical interface
Matias N Goldberg avatar
vg flag
If you type `env` in the console you can see all the environment variables set for that console. Start removing them until your app stops working to narrow down which ones you need
MemoNick avatar
in flag
@MatiasNGoldberg Thank you, that worked!
Score:0
in flag

As Matias commented, the solution was to find the missing environment variables. In my case, it was XDG_RUNTIME_DIR=/run/user/1000.

My final service looks like this:

[Unit]
Description=Auto-ducker
After=multi-user.target
[Service]
Environment=XDG_RUNTIME_DIR=/run/user/1000
Type=simple
Restart=always
User=nicholas
Group=nicholas
ExecStart=/path/to/venv/bin/python /path/to/main.py
[Install]
WantedBy=multi-user.target
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.