Find the length of a wav file in Ruby

I needed a way to find out quickly the length of the wav file. in a previous version, I was simply guessing it from the file size, saying that a wav file is about a megabyte per minute. but that ain't the proper way. Thanks to this site giving me the wav file header. I could quickly write my own in Ruby.

def wavinfo(input) def bytes_to_int(bytes) bytes.unpack("L").first end # try to load a file form the filesystem unless we got a data stream as a parameter unless input[0..3] == 'RIFF' file = File.new(input,"r") input = file.read(45) file.close end return { :filesize => (8 + bytes_to_int(input[4..7])), :wavefmt => input[8..15], :format => bytes_to_int(input[16..19]), :pcm => bytes_to_int(input[20..21]), :channels => bytes_to_int(input[22..23]), :frequency => bytes_to_int(input[24..27]), :bytes_per_second => bytes_to_int(input[28..31]), :bytes_by_capture => bytes_to_int(input[32..33]), :bits_per_sample => bytes_to_int(input[34..35]), :always_data => input[36..39], :bytes_in_data => bytes_to_int(input[40..43]), :wav_length => bytes_to_int(input[40..43]).to_f / bytes_to_int(input[28..31]), } end hope this helps you

Tags , , , , ,

Posted in , , | Posted on 16 Feb 2011 06:52by somekool |

Subscribe

my last twitter posts

Personal Links

Tags

Categories

Archives

my Xbox 360 gamertag

Copyright © Mathieu Jobin's Life and Thoughts