views:

120

answers:

1

I am building a pure-Ruby WAV file read/write library, learning deeper Ruby functionality as I go. It currently works well with 16-bit audio, as I am able to use String.unpack('s*') to pull individual audio samples out into an array of signed integers. I am having trouble wrapping my mind around how to go about dealing with 24-bit audio, however. Each sample in that case is 3 bytes long. What pack/unpack string would you recommend in that case, and would I likely have to drastically alter my approach (using padding or something like that)?

+1  A: 

As you used unpack("s+") , i assume your sample are in big endian. Here is a not-so-fast but workable solution.

>> "ABCDEF".scan(/.../).map {|s| (s.reverse + 0.chr ).unpack("V")}.flatten
=> [4276803, 4474182]    #=> [0x414243, 0x444546] in HEX
pierr
`[4276803, 4474182].map { |s| [s].pack("VX").reverse }.join` seems to do the trick in reverse.
Aaron Cohen
Looks like my samples turned out to be little endian, so I didn't need the reverse. The `0.chr` was the key...it needed to be padded out for the unpack to work properly. Many thanks.
Aaron Cohen