Skip to content

Instantly share code, notes, and snippets.

@dluciv
Last active January 20, 2022 10:54
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 dluciv/ee90ba05f0a1e2c59452cc70cdea3f22 to your computer and use it in GitHub Desktop.
Save dluciv/ee90ba05f0a1e2c59452cc70cdea3f22 to your computer and use it in GitHub Desktop.
Mac OS get & set output volume from command line
#!/usr/bin/env zsh
mac_max_set=100.0
mac_max_get=100.0
# $ brew install blackhole-2ch switchaudio-osx
# https://github.com/ExistentialAudio/BlackHole
# https://github.com/deweller/switchaudio-osx
# made my day.
# But when first one is used within default output of multi-output device, AppleScript Fails to get output volume.
# So as a fallback, second one helps to temporarily switch to default output to just get volume.
# Hey! Hey, Apple! I bet you can't spit orange juice!
switch_ad_to(){
# get current device
if cur_dev=$(SwitchAudioSource -c) 2>/dev/null
then
SwitchAudioSource -s "$1" &>/dev/null
echo -n $cur_dev
else
exit 1
fi
}
getv(){
osa_output=$(osascript -e "(output volume of (get volume settings))")
# oscacript will not even set exit status when getting an error
if normalized_value=$(echo $(( ${osa_output} / $mac_max_get )) ) 2>/dev/null
then
LC_ALL=C printf "%0.2f\n" $normalized_value
elif cur_device=$(switch_ad_to "Built-in Output") && [[ "$cur_device" != "Built-in Output" ]]
then
v=$(getv) # retry...
switch_ad_to "$cur_device" &>/dev/null
echo $v
else # nothing helps
>&2 echo get volume returned: $osa_output
exit 1
fi
}
setv(){
if (( $1 < 0 )); then
a=0.0
elif (( $1 > 1 )); then
a=1.0
else
a=$(LC_ALL=C printf "%0.2f" $(( $1 * $mac_max_set )) )
fi
# "set volume ..." was expecting values between 0.0 and 7.0
osascript -e "set volume output volume ${a}"
}
incv(){
if old_value=$(getv)
then
setv $(($old_value $1))
else
>&2 echo 'Not (inc/dec)rementing volume as could not read it'
exit 1
fi
}
case $1 in
s)
setv $2
;;
g)
getv
;;
i)
incv '+ 0.05'
;;
d)
incv '- 0.05'
;;
esac
@dluciv
Copy link
Author

dluciv commented Jan 20, 2022

Actually this one does almost everything good enough https://github.com/karaggeorge/macos-audio-devices

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