Skip to content

Instantly share code, notes, and snippets.

@jtzemp
Forked from companygardener/Ruby FFT of .wav Test.rb
Created October 30, 2010 05:09
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 jtzemp/654980 to your computer and use it in GitHub Desktop.
Save jtzemp/654980 to your computer and use it in GitHub Desktop.
#!/user/bin/env ruby
require 'rubygems'
require 'wavefile'
require 'fftw3'
require 'fastercsv'
# needs to be mono, or you'll need to discard a channel, or combine channels
w = WaveFile.open('sample.wav')
samples = w.sample_data[0, [w.sample_rate * 10, w.sample_data.size].min]
duration = samples.size / w.sample_rate
na = NArray.float(2, samples.size)
samples.each_with_index do |v, i|
na[0, i] = i.to_f / w.sample_rate.to_f
na[1, i] = v # if the file is stereo, do v.first or v.last or v[0] + v[1]
end
fa = FFTW3.fft(na)
fa = fa.real.abs # you probably need absolute values for magnitudes of a frequency to make sense
FasterCSV.open('output.csv', 'w') do |csv|
0.upto((fa.total / fa.dim) - 1) do |i|
csv << fa[true, i].to_a
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment