Skip to content

Instantly share code, notes, and snippets.

@madacol
Last active June 25, 2020 17:53
Show Gist options
  • Save madacol/1a0d8569166886d2d98f073f7f5c5fe3 to your computer and use it in GitHub Desktop.
Save madacol/1a0d8569166886d2d98f073f7f5c5fe3 to your computer and use it in GitHub Desktop.

Moved

Up-to-date version here: https://github.com/madacol/sinkSwitcher


How to use this

Each script is independent from each other.

  • Download whichever you want.
  • Make it executable i.e. chmod +x sinkSwitcher.sh.
  • Add a keyboard shortcut to execute each script. Note: I had to install compizconfig-settings-manager to set the shorcuts. sudo apt-get install compizconfig-settings-manager.

How it works

sinkDefaultSwitcher.sh:

Rotates the default sink among the available audio output devices (I only use this to be able to change volume)

sinkSwitcher.sh:

Detects the focused application, find all belonging sink-inputs and switch them to next sink.

#!/bin/bash
#######
# Dependencies: pulseaudio
# USAGE: Execute script and default sink will switch
#######
sink_list_array=( $(pacmd list-sinks | awk '/index:/{print $NF}') )
sink_list_size=${#sink_list_array[@]}
current_sink_index=$(pacmd list-sinks | awk '/* index:/{print $NF}')
i=0
for sink in "${sink_list_array[@]}"; do
i=$((($i+1)%sink_list_size)) #i++
echo $sink $i $current_sink_index
if [ $sink = $current_sink_index ]; then
next_sink_index=${sink_list_array[i]}
break
fi
done
pacmd set-default-sink $next_sink_index
#!/bin/bash
#######
# Dependencies: pulseaudio, xprop
# Optional: compizconfig-settings-manager. To configure this script with a keyboard shortcut.
# USAGE: Focus the application you want to change its sink and run this script.
# This scripts detects the focused application, find all belonging sink-inputs and switch them to next sink.
# Intended to run with a shortcut.
#######
# Find PID of focused window
xid=$(xprop -root _NET_ACTIVE_WINDOW | awk '{print $NF}')
app_pid=$(xprop -id $xid _NET_WM_PID | awk '{print $NF}')
sink_list_array=( $(pacmd list-sinks | awk '/index:/{print $NF}') )
sink_list_size=${#sink_list_array[@]}
# Linearizes sink-inputs, showing index, sink and pid on a same line, and iterate through each line.
pacmd list-sink-inputs | grep -E 'index:|sink:|process.id' | tr '\n' ' ' | tr -d '"' | sed -e 's/index:/\n/g' | tail -n +2 | while IFS= read -r line || [ -n "$line" ]; do
sink_input_pid=$(echo $line | awk '{print $NF}')
# Check if sink-input's app matches with the focused app
if [ $sink_input_pid = $app_pid ]; then
sink_input_index=$(echo $line | awk '{print $1}')
current_sink_index=$(echo $line | awk '{print $3}')
i=0
for sink in "${sink_list_array[@]}"; do
i=$((($i+1)%sink_list_size)) #i++
if [ $sink = $current_sink_index ]; then
next_sink_index=${sink_list_array[i]}
break
fi
done
pacmd move-sink-input $sink_input_index $next_sink_index
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment