Saturday, August 22, 2020

Starting JACK automatically when a USB audio device is connected

I have a Raspberry Pi that I'm using headless for audio, and I wanted to automatically start jackd when I connected my USB audio device.

There are a lot of ways to try to do this - after a few false starts, I ended up with this method. It took me long enough to sort out the details that I figured I'd write up a little how-to.

This solution is composed of two parts: 1) set up jackd as a systemd service, and 2) use a udev rule to start the service when the sound card is connected.

First the service. Create a file called '/etc/systemd/system/jackd.service' with the following:

[Unit]
Description=JACK audio
After=network.target

[Service]
ExecStart=/usr/bin/jackd <your jack commandline arguments here>
WorkingDirectory=/usr/local/bin
StandardOutput=inherit
StandardError=inherit
Restart=always
User=root

[Install]
WantedBy=multi-user.target

Now (or at least after you reboot, or do 'sudo systemctl daemon-reload', you can start and stop jackd with 'sudo systemctl start jackd.service' and 'sudo systemctl stop jackd.service'. I'm running the service as root - if you want to use a different user, change the "User=" line.

We want this to happen automatically, though, so it is time to use udev - the system for managing Linux device events.

First, you need to know some information about your USB audio device. Plug it in, and run 'lsusb'. You should see something like this:

Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 0582:01d6 Roland Corp.
Bus 001 Device 002: ID 2109:3431 VIA Labs, Inc. Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Look for your sound card device in the list (mine is showing as "Roland Corp."), and note the two hex numbers after ID. They are the USB Vender and Product IDs for your device.

Create a file called something like '/etc/udev/rules.d/80-local.rules' with the following in it:

ACTION=="add", ATTR{idVendor}=="0582", ATTR{idProduct}=="01d6", TAG+="systemd", ENV{SYSTEMD_WANTS}="jackd.service"

Where the values for 'ATTR{idVendor}' and 'ATTR{idProduct}' are the Vendor and Product IDs you got from lsusb.

After your next reboot, or after running 'sudo udevadm control --reload', you new rule should be ready. When you plug in your sound card, the udev rule will fire and request your service, which will then start jackd.

No comments:

Post a Comment