pythondebiandbuspulseaudio

How to resolve PulseAudio connection test failed: Failed to connect to pulseaudio server?


Multiple days now I have been trying to setup a python service that runs on debian and streams music via bluetooth. The bluetooth part works fine. I am using dbus. The problem comes with the `pulsectl` pulse audio service running on the debian computer. The error is below. It keeps telling that it cannot find the `/run/user/1001/pulse` directory but when I do `ls` it is already there.

:Failed to create secure directory (/run/user/1001/pulse): No such file or directoryNov 28 14:32:59 triton python3[550]: ERROR app.root - PulseAudio connection test failed: Failed to connect to pulseaudio serverNov 28 14:32:59 triton python3[550]: ERROR app.root - Cannot connect to PulseAudio server. Exiting...

I have some logic to first check if `pulsectl` is connected or not and this is where it breaks:

def test_pulseaudio_connection():
    try:
        with pulsectl.Pulse("test-connection") as pulse:
            return True
    except Exception as e:
        logging.error(f"PulseAudio connection test failed: {e}")
        return False


if __name__ == "__main__":
    os.environ["XDG_RUNTIME_DIR"] = f"/run/user/{os.getuid()}"

    # First, test the PulseAudio connection
    if not test_pulseaudio_connection():
        logging.error("Cannot connect to PulseAudio server. Exiting...")
        exit(1)  # Exits the program if PulseAudio is not running

Also I I have setup the systemd service file with passing and environment file there and also choosing user to run this etc because I read that it should not be the root running pulseaudio service.

[Service]ExecStart=/usr/bin/python3 /opt/backend/src/app.py
WorkingDirectory=/opt/backend/src
Environment="XDG_RUNTIME_DIR=/run/user/1001"
Environment="ENVIRONMENT=development"
User=user
Group=audio
Group=root
Restart=always
[Device]
DeviceAllow=/dev/ttyRS232_A rw
[Install]WantedBy=multi-user.target

I have no idea why it keeps showing this error.


Solution

  • but when I do ls it is already there

    User runtime directories are not created at boot time – their existence is tied to existence of interactive login session. So it is 'already there' after you log in, but it wasn't yet 'already there' when the service started during system boot before you logged in to check.

    Use loginctl enable-linger $USER to configure systemd to create the user's runtime directory on boot (as well as start that user's personal "systemctl --user" services on boot).

    Then, either add an After=user-runtime-dir@1000.service dependency to make sure things happen in the correct order, or (preferably) convert your whole service to a "--user" service in ~/.config/systemd/user/.