Skip to content

Instantly share code, notes, and snippets.

@shuairan
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuairan/51c0a9452e60a3308a2f to your computer and use it in GitHub Desktop.
Save shuairan/51c0a9452e60a3308a2f to your computer and use it in GitHub Desktop.
change Pulseaudio volume from command line. BE CAREFUL: Setting the volume higher than 150% may harm your device or speakers!
#!/bin/bash
CRITICAL_LIMIT=153
SINK=1
input="$@"
new_vol=0
function usage {
echo "Usage: $(basename $0) [+/-]INT"
echo " INT: absolute value or relative (with leading +/-)"
}
function get_sink_volume {
SINK_NO=$1
sink_vol=$(pactl list sinks | sed -n -e "/Sink #$SINK_NO/,\$p" | grep '^\sVolume: ' | awk '{print $5}')
sink_vol=${sink_vol%"%"}
echo $sink_vol
}
function get_relative_volume {
SINK_NO=$1
cur_vol=$2
change=${input:0:1}" "${input:1}
new_vol=$(expr $cur_vol $change)
if [[ new_vol -gt 0 ]]; then new_vol=0; fi
echo $new_vol
}
if [[ -z $input ]]; then
echo "Current Volume: $(get_sink_volume $SINK)%"
fi
if ! [[ $input =~ ^[-|+]?[0-9]+$ ]]; then
usage
exit
fi
cur_vol=$(get_sink_volume $SINK)
if [[ $input =~ ^[-|+] ]]; then
# Relative input:
new_vol=$(get_relative_volume $SINK $cur_vol)
echo "Current volume: $cur_vol%. New Volume: $new_vol%"
else
# Absolute Input
new_vol=$input
fi
ask=$(expr $new_vol / 150)
if [[ $cur_vol -lt $new_vol ]] && [[ $new_vol -gt $CRITICAL_LIMIT ]]; then
while true; do
read -p "$new_vol%?: Are you sure?" yn
case $yn in
[Yy]* ) if [[ $ask -gt 1 ]]; then ask=$(expr $ask - 1); echo "Really? Answer 'y' $ask more times!"; continue;
else echo "okay!"; break
fi
;;
[Nn]* ) echo "canceled"; exit;;
* ) echo "Please answer yes or no.";;
esac
done
fi
VOL=$(expr $new_vol \* 65536 / 100)
echo "setting volume to $new_vol% ($VOL)"
pacmd set-sink-volume $SINK $VOL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment