Very Simple Metronome in Ruby

A metronome is basically something that beeps periodically, indicating the exact tempo of some music. I wanted one for my guitar practice, but the only one in Ubuntu’s repos (GTick) wouldn’t work, so I wrote this up.

# Emit a tick
def beep
  Thread.new { print "\a" }
end
 
def every(delay)
  loop do
    sleep(delay)
    yield
  end
end
 
# Get the BPM
if ARGV[0] == nil
  puts "Enter the BPM"
  bpm = gets.to_f
else
  bpm = ARGV[0].to_f
end
 
# Convert beats per minute to the number of seconds to wait. For 
# example, a bpm of 60 would equal a one second wait.
delay_seconds = 60.0 / bpm
 
every delay_seconds { beep }

If you want to change how the beeping happens, you only have to edit the beep method right at the top. To do that on Windows, have a look at this post on the win32-sound library. On Linux you could write to /dev/dsp but it might be better to use ALSA. The ruby/audio library is also worth having a look over.

Tags: , , , ,

2 Responses to “Very Simple Metronome in Ruby”

  1. Archit says:

    Well it does work for me but i have a nagging doubt regarding the definition of ARGV used here. Explain please.

    • Vikhyat Korrapati says:

      ARGV is an array that contains the command line arguments that were passed to that program. For example, if you invoke ruby awesomeprogram.rb my awesome command line arguments, then ARGV = %w[ my awesome command line arguments ]. I have it that way so you could pass it a parameter, ie run it this way: ruby metronome.rb 102.

Leave a Reply