Skip to content

Instantly share code, notes, and snippets.

Created November 12, 2010 00:41
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dbrady/673524 to your computer and use it in GitHub Desktop.
Interleaved Unpacking...
# This takes about 2s for a 53Mb file.
bytes = audio_file.read_into(audio_buffer)
# This takes less than a second, BUT the data is interleaved
# (left, right, left, right, left, right, etc)
self.audio_data = audio_buffer.unpack('s*')
# Less than a second.
self.left_channel = NArray.float(2, audio_data.size)
self.right_channel = NArray.float(2, audio_data.size)
# This loop takes about 40-50 seconds. Rewriting it to eliminate
# all division and multiplication shaves about 10s off that time.
0.upto(audio_data.size/2-1) do |i|
time = i.to_f / audio_file.rate
# First array stores time offset of sample
left_channel[0, i] = time
right_channel[0, i] = time
# Second array stores sampled data
left_channel[1, i] = audio_data[i*2]
right_channel[1, i] = audio_data[i*2+1]
# BUT!
# If I could avoid the Ruby loop altogether, and let something
# like NArray's constructors handle it, it's a 10x speedup. For
# example:
# interleaved_data = NArray[self.audio_data]
# Takes less than 4 seconds! This is because we're not looping in
# Ruby, but letting C handle the grindy stuff. However, the data
# is interleaved, making it useless for processing rationally. :-/
# I can separate it back out with another loop, but guess how long
# that takes....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment