Created
February 19, 2014 14:48
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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