Skip to content

Instantly share code, notes, and snippets.

@nanki
Created September 20, 2011 16:33
Show Gist options
  • Save nanki/1229587 to your computer and use it in GitHub Desktop.
Save nanki/1229587 to your computer and use it in GitHub Desktop.
ASCII equalizer.
require 'ffi'
module FFI::PortAudio
module API
extend FFI::Library
ffi_lib 'portaudio'
Int16 = 0x8
FramesPerBufferUnspecified = 0
class PaStreamParameters < FFI::Struct
layout(
:device, :int,
:channelCount, :int,
:sampleFormat, :ulong,
:suggestedLatency, :double,
:hostApiSpecificStreamInfo, :pointer)
end
callback :PaStreamCallback, [:pointer, :pointer, :ulong, :pointer, :ulong, :pointer], :int
attach_function :Pa_Initialize, [], :int
attach_function :Pa_Terminate, [], :int
attach_function :Pa_GetDefaultInputDevice, [], :int
attach_function :Pa_OpenStream, [:pointer, :pointer, :pointer, :double, :ulong, :ulong, :PaStreamCallback, :pointer], :int
attach_function :Pa_CloseStream, [:pointer], :int
attach_function :Pa_StartStream, [:pointer], :int
attach_function :Pa_StopStream, [:pointer], :int
attach_function :Pa_Sleep, [:long], :void
end
end
include FFI::PortAudio
API.Pa_Initialize
input = API::PaStreamParameters.new
input[:device] = API.Pa_GetDefaultInputDevice
input[:channelCount] = 1
input[:sampleFormat] = API::Int16
maxmin = [nil, nil]
callback = lambda {|input, _, frameCount, _, _, _|
v = input.read_array_of_int16(frameCount).inject(0){|r, i| r + i.abs }
maxmin = [
[maxmin[0] || v, v].max,
[maxmin[1] || v, v].min
]
max, min = maxmin
v = (max - min) == 0 ? 1 : (v - min).quo(max - min)
print "¥e[#{31 + (6 * v).to_i}m"
puts "*" * (v * 80).to_i
}
stream = FFI::Buffer.new(:pointer)
API.Pa_OpenStream(stream, input, nil, 44100, 700, 0, callback, nil)
API.Pa_StartStream stream.read_pointer
at_exit do
API.Pa_CloseStream(stream)
API.Pa_Terminate
end
loop { sleep 1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment