Skip to content

Instantly share code, notes, and snippets.

@zqu4rtz
Last active September 15, 2023 00:57
Show Gist options
  • Select an option

  • Save zqu4rtz/0479e9b780f78a1e46d0b4f9a8e42607 to your computer and use it in GitHub Desktop.

Select an option

Save zqu4rtz/0479e9b780f78a1e46d0b4f9a8e42607 to your computer and use it in GitHub Desktop.
Simple bash Script to Auto Connect Midi Devices, and use Linux Host (i.e. Raspberry) as a Midi Host.
#!/bin/bash
# This script will connect all masters to slaves
# So the communication is only unidirectional.
# Some midi devices can act as input and output, so differentiating them
# Helps to prevent unwanted communications between devices
# Identiy Master and Slaves using names
# Put here the masters (or devices that will act as inputs of other devices)
declare -a MASTERS=("Elektron Syntakt")
# Put here the slaves (or devices that will produce sound)
declare -a SLAVES=("NTS-1 digital kit")
# Erase all midi routes configured previously
printf "Cleanning existing midi connections...\n"
aconnect -x
IFS=""
for m in ${MASTERS[@]}; do
ac_inputs=$(aconnect -i -l | grep "$m")
m_client_id=$(printf "$ac_inputs\n" | awk -F ':' '{print $1;exit}' | sed 's/client\s//')
m_client_port=$(printf "$ac_inputs\n" | awk '{getline;print}' | awk '{print $1}')
m_client=$(printf "$m_client_id:$m_client_port")
if [ ! -z "$m_client_id" ];
then
for s in ${SLAVES[@]}; do
ac_outputs=$(aconnect -o -l | grep "$s")
s_client_id=$(printf "$ac_outputs\n" | awk -F ':' '{print $1;exit}' | sed 's/client\s//')
if [ ! -z "$s_client_id" ];
then
s_client_port=$(printf "$ac_outputs\n" | awk '{getline;print}' | awk '{print $1}')
s_client=$(printf "$s_client_id:$s_client_port")
if [ "$m_client" != "$s_client" ];
then
printf "Connecting devices. Input: $m. $m_client. Output: $s. $s_client\n"
aconnect "$m_client" "$s_client"
fi
else
printf "Ignoring: $s. Output Device not found \n"
fi
done
else
printf "Ignoring: $m. Input Device not found\n"
fi
done
@zqu4rtz
Copy link
Author

zqu4rtz commented Sep 13, 2023

Before executing the script, you need to identify which devices will act as input (MASTERS) and which will act as output (SLAVES). In the above example I used as input "Elektron Syntakt" and output "NTS-1 Nutekt"

You can use it along with udev rules to execute it automatically when a new USB-MIDI interface is connected.

ACTION=="add|remove", SUBSYSTEM=="usb", DRIVER=="snd-usb-audio", RUN+="/usr/local/bin/auto-connect-midi.sh"

Don't forget to reload the udev rules:

sudo udevadm control --reload
sudo systemctl restar udev

You can also define a Systemd service descriptor to execute it automatically at boot.

[Unit]
Description=Auto Connect MIDI Devices

[Service]
ExecStart=/usr/local/bin/auto-connect-midi.sh

[Install]
WantedBy=multi-user.target

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment