Skip to content

Instantly share code, notes, and snippets.

@phil-monroe
Created February 19, 2014 14:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save phil-monroe/9093566 to your computer and use it in GitHub Desktop.
Save phil-monroe/9093566 to your computer and use it in GitHub Desktop.
Use CoreAudio with Ruby to make a real time CLI level meter and frequency response chart
require "thread"
require "fftw3"
require "coreaudio"
require 'ruby-progressbar'
# progressbar = ProgressBar.create
# progressbar.total = 100
Thread.abort_on_exception = true
BUF_SIZE=1024*4
inbuf = CoreAudio.default_input_device.input_buffer(BUF_SIZE)
PEAK = 65535.0
@mutex = Mutex.new
@db = nil
@f = nil
run = true
th = Thread.start do
loop do
wav = inbuf.read(BUF_SIZE)
amp = wav.abs.max.to_f
@mutex.synchronize do
@db = 20 * Math.log(amp / PEAK)
@f = FFTW3.fft(wav, 1).abs/wav.length
end
end
end
inbuf.start
Signal.trap("SIGINT") { run = false}
sleep 1
while run
db = nil
f = nil
@mutex.synchronize do
db = @db
f = @f
end
system("clear")
print "#{db.to_i} dB |"
(db.to_i + 100).times { print "=" }
puts
puts "frequency:"
freq = f.to_a.map(&:first)[0...300].map{|i| i.to_i }
freq.each_with_index{|i, idx| puts(("%3d |"%idx)+("D"*[360,i].min)) if idx % 2 == 0 }
puts freq.length
sleep 0.1
end
inbuf.stop
th.kill.join
#
#
#
puts "#{inbuf.dropped_frame} frame dropped at input buffer."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment