Skip to content

Instantly share code, notes, and snippets.

@keithrbennett
Last active May 11, 2019 17:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keithrbennett/fcf8d1511a430dd2cbc3bafdfe81ba59 to your computer and use it in GitHub Desktop.
Save keithrbennett/fcf8d1511a430dd2cbc3bafdfe81ba59 to your computer and use it in GitHub Desktop.
Controls and displays volume settings on the Mac command line.
#!/usr/bin/env ruby
# This file's home is at https://gist.github.com/keithrbennett/fcf8d1511a430dd2cbc3bafdfe81ba59.
# With a numeric argument from 0 to 100,
# sets volume to that %, and outputs new volume settings.
#
# Without any argument, outputs volume settings.
# Author: Keith Bennett (keithrbennett on Github)
# Strangely, the argument to "osascript -e 'set volume..." is in the range
# 0 to 7, where 0 is 0% volume and 7 is 100% volume, while
# the utility that prints the volume prints the percent:
#  osascript -e 'get volume settings'
# output volume:50, input volume:100, alert volume:100, output muted:false
# We need to round the percent numbers because the underlying Mac utility
# returns integral percents (i.e. 33%, not 33.3%).
def percent_to_range_0_7(percent)
percent / (100 / 7.0)
end
def current_volume_percent
text = `osascript -e 'get volume settings'`
text.split(',').first.split(':').last.to_f.round(0)
end
def set_volume(percent)
arg_0_to_7 = percent_to_range_0_7(percent)
cmd = "osascript -e 'set volume #{arg_0_to_7}'"
`#{cmd} 2>&1`
end
def main
old_volume = current_volume_percent
volume_change_requested = (ARGV.length > 0)
if volume_change_requested
requested_volume = ARGV[0].to_f.round(0)
if old_volume == requested_volume
puts "No need to change volume. Already at #{old_volume}%."
else
set_volume(requested_volume)
new_volume = current_volume_percent
puts "Changed volume from #{old_volume}% to #{new_volume}%."
end
else
puts "Volume is currently at #{old_volume}%."
end
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment