Last active
April 19, 2018 14:27
-
-
Save danhalliday/3508820 to your computer and use it in GitHub Desktop.
A quick start on a BinData wrapper for WAV files
This file contains 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
#!/usr/bin/ruby | |
# This is a quick skeleton of how to read a Wave file in ruby using the BinData gem. | |
# There are many different chunk types and bit depths that should be accounted for! | |
require 'rubygems' | |
require 'bindata' | |
class Wave < BinData::Record | |
endian :little | |
# Riff | |
int32be :chunk_id | |
int32 :chunk_size | |
int32be :riff_type | |
# FMT | |
int32be :fmt_chunk_id | |
int32 :fmt_chunk_size | |
int16 :compression_code | |
int16 :number_of_channels | |
int32 :sample_rate | |
int32 :bytes_per_second | |
int16 :block_align | |
int16 :bits_per_sample | |
# Data | |
string :data_chunk_id, :read_length => 4 | |
uint32 :data_chunk_size | |
array :samples, | |
:type => :int16, # Or int24 | |
:initial_length => 44100 | |
end | |
# Use it! | |
wave = Wave.new.read File.open("track.wav") | |
puts "Duration: #{ wave.data_chunk_size / wave.bytes_per_second } seconds." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment