Created
June 24, 2020 22:16
-
-
Save AfonsoFGarcia/7309cbbeb3c1d166c21a75277dd0a427 to your computer and use it in GitHub Desktop.
Switch audio ouputs from the command line in Ubuntu
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Define the name of the sinks to use | |
readonly HEADPHONES="alsa_output.usb-Roland_DUO-CAPTURE-00.analog-stereo" | |
readonly SPEAKERS="alsa_output.pci-0000_0d_00.4.iec958-stereo" | |
# Get the current sink | |
currentSink=$(pactl info | grep "Default Sink" | awk '{print $3}') | |
# Based on the current sink, switch between cards | |
if [ $currentSink == $HEADPHONES ]; then | |
newSink=$SPEAKERS | |
else | |
newSink=$HEADPHONES | |
fi | |
# Get the first sink index to check if an offset is needed | |
firstSinkIndex=$(pactl list short sinks | head -n 1 | awk '{print $1}') | |
# Compute the offset based on the first sink index | |
if [ $firstSinkIndex == 0 ]; then | |
sinkOffset=1 | |
else | |
sinkOffset=0 | |
fi | |
# Get the index of the new sink | |
sinkIndex=$(pactl list short sinks | grep "$newSink" | awk '{print $1}') | |
# Get the volume of the new sink | |
currentVolume="$(pactl list sinks | grep '^[[:space:]]Volume:' | head -n $(( $sinkIndex + $sinkOffset )) | tail -n 1 | sed -e 's,.* \([0-9][0-9]*\)%.*,\1,')%" | |
# Set the volume of the new sink (this enables ubuntu's media controls for some reason) | |
pactl set-sink-volume $newSink $currentVolume | |
# Set the default sink to the new sink | |
pactl set-default-sink $sinkIndex | |
# Move all active streams to the new sink | |
pactl list short sink-inputs|while read stream; do | |
streamId=$(echo $stream|cut '-d ' -f1) | |
pactl move-sink-input "$streamId" "$newSink" | |
done | |
# Display nice notification about which sink is being used | |
if [ $newSink == $HEADPHONES ]; then | |
notify-send 'Audio output switched' 'Now playing sound from the headphones' --icon=audio-card | |
else | |
notify-send 'Audio output switched' 'Now playing sound from the speakers' --icon=audio-card | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment