Skip to content

Instantly share code, notes, and snippets.

@SwagDevOps
Last active March 17, 2018 14:45
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 SwagDevOps/9331f9d79df1ff60a9f681ea2e7a3f6a to your computer and use it in GitHub Desktop.
Save SwagDevOps/9331f9d79df1ff60a9f681ea2e7a3f6a to your computer and use it in GitHub Desktop.
Simple Volume Control based on ``pactl``
#!/usr/bin/env ruby
require 'shellwords'
# Simple Volume Control based on ``pactl``
#
# Sample of (CLI) use:
#
# ```
# volume-control up
# volume-control down
# volume-control toggle-mute
# volume-control to 50
# volume-control set 50
# ```
class VolumeControl
attr_reader :sink
attr_reader :increment
def initialize(sink = 0, increment = 5)
@sink = sink
@increment = increment
end
# Increase volume
def sink_up
execute(:up)
end
# Decrease volume
def sink_down
execute(:down)
end
# Set volume to given ``volume``
#
# @param [Fixnum] volume
def sink_to(volume)
execute(:to, volume: volume.gsub(/%$/, '').to_i)
end
alias sink_set sink_to
# Toggle mute
def sink_toggle_mute
execute(:toggle_mute)
end
# Get arguments
#
# @return [Hash]
def arguments
{
toggle_mute: ['set-sink-mute', sink, :toggle],
up: ['set-sink-volume', sink, "+#{increment}%"],
down: ['set-sink-volume', sink, "-#{increment}%"],
to: ['set-sink-volume', sink, "%<volume>s%"],
}
end
# Get command for given ``keyword``
#
# @param [Symbol] keyword
# @param [Hash] options
# @return [Array<String>]
def command(keyword, options = {})
[:pactl].concat(arguments.fetch(keyword.to_sym))
.map(&:to_s)
.map { |s| s % options }
end
protected
# Execute ``system`` command for given ``keyword``
#
# @param [Symbol] keyword
# @param [Hash] options
# @return [Boolean]
def execute(keyword, options = {})
command = self.command(keyword, options)
puts '# %<command>s' % { command: Shellwords.shelljoin(command) }
system(*command)
end
end
if __FILE__ == $0
action = 'sink_%<action>s' % { action: ARGV.fetch(0).tr('-', '_') }
VolumeControl.new.public_send(action, *ARGV.drop(1)) || exit(1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment