Created
July 22, 2010 22:27
-
-
Save companygardener/486711 to your computer and use it in GitHub Desktop.
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
#!/user/bin/env ruby | |
require 'rubygems' | |
require 'wavefile' | |
require 'fftw3' | |
require 'fastercsv' | |
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 - 1] = i.to_f / w.sample_rate.to_f | |
na[1, i - 1] = v | |
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
Ran into a weird bug using this code. FYI, if you get this error:
fouriertest.rb:16:in
[]=': end-index=2 is out of dst.shape[0]=2 (IndexError) from fouriertest.rb:16 from /Users/dbrady/.rvm/rubies/ruby-1.8.7-p249/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in
each_with_index'from fouriertest.rb:14:in
each' from fouriertest.rb:14:in
each_with_index'from fouriertest.rb:14
It's because the wavefile you're processing is in stereo. On line 16, v is actually a pair of values, [left, right]. To process just the left channel, change line 14 to read
Also, each_with_index starts at 0; using i-1 as the index puts the first sample at the end of the NArray. There is no observable effect from this since you're ALSO putting the first timestamp at the end of the NArray, and Fourier doesn't care about element order. :-)