Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Toggles between two audio outputs.
- # Note: Only works with a maximum of two audio outputs.
- # Note: `pacmd` does not report its exit code to Bash, and does not print errors to stderr. I don't know why not, but that's how it is. It's better to use `pactl` for one-off commands.
- # What to do if there is an error.
- switch_error(){
- echo "Error: $error"
- zenity --error \
- --title="$(basename "$0")" \
- --text="$error\n$(basename "$0") cancelled."
- exit 1
- }
- # The sink (output) that is not currently in use.
- next_sink="$(pacmd list-sinks | fgrep -v '*' | grep 'index' | grep -Eo '[0-9]{1,10}')"
- # Input to the sinks.
- sink_inputs="$(pacmd list-sink-inputs | grep 'index' | grep -Eo '[0-9]{1,10}')"
- # Preliminary checks.
- # Exits if less than two audio outputs are detected.
- if [[ -z "$next_sink" ]]; then
- error="Fewer than two audio outputs detected."
- switch_error
- # Confirms there are not more than two audio sinks, by looking for a space in the sink listing.
- elif echo "$next_sink" | grep -q ' '; then
- error="More than two audio outputs detected."
- switch_error
- fi
- # Moves any currently playing audio streams to the new sink.
- for i in $sink_inputs; do
- move_sink_input="$(pactl move-sink-input "$i" "$next_sink")"
- if [[ -z "$move_sink_input" ]]; then
- echo 'Switched sink input '"$i"' onto sink '"$next_sink"
- else
- >&2 echo "Error: pactl: $move_sink_input"
- error="Could not move sink input."
- switch_error
- fi
- done
- # Changes the default sink.
- set_default_sink="$(pactl set-default-sink "$next_sink")"
- if [[ -z "$set_default_sink" ]]; then
- echo 'Switched default audio output to sink '"$next_sink"
- else
- >&2 echo "Error: pactl: $set_default_sink"
- error="Could not switch default sink."
- switch_error
- fi
- # Finds info about the new sink.
- sink_info="$(pacmd list-sinks | grep -A 1 '* index')"
- # Reports the name of the new sink.
- if [[ "$sink_info" == *"Logitech_Wireless_Headset"* ]]; then
- sink_name="Logitech wireless headset"
- elif [[ "$sink_info" == *"pci-0000_00_1b.0.analog-stereo"* ]]; then
- sink_name="built-in audio"
- else
- sink_name="$(echo "$sink_info" | grep 'name' | cut -d'<' -f2 | cut -d'>' -f1)"
- fi
- # Shows more info in terminal.
- echo 'Audio output now '"$sink_name"
- # Shows a notification.
- if [[ -n "$sink_inputs" ]]; then
- notify_sink_inputs="\nMoved currently playing audio streams."
- fi
- killall notify-osd
- notify-send "Audio output" 'Switched to '"$sink_name.$notify_sink_inputs"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement