Joel VanderWerf
10/23/2006 7:55:00 AM
Rob Lee wrote:
> Hi
>
> I've been modifying a binary file that contains various data including
> some audio. I'm trying to add my own audio (instead of the audio in the
> file) which I believe I have done but I need to modify the
> content-length header in the file which indicates the length of the
> audio sample. I've been reading the content-length data from the file
> using something similar to :
>
> f=open(config[:file],"rb")
> f.pos=AUDIO_CONTENT_HEADER_OFFSET
> length=f.read(3).unpack("H2H2H2").hex.to_i
> f.close
> => an integer
>
> This basically opens the file as a binary file, skips to the audio
> content header data position and then unpacks 3 bytes into a string
> (formatted as hex) which is then converted to an integer value.
>
> I'd like to be able to reverse this process and take any an integer
> value (1024 in the case shown below) and write it to a binary file with
> some header and footer data - something like :
>
> mydata = SOMEHEADERDATA
> mydata += ["1024"].pack("someformat")
> mydata += AUDIODATA
> f=open(config[:file],"wb")
> f.write(mydata)
> f.close
>
> However I'm a bit stuck on how to pack the data (if this is the correct
> solution). If someone could point me in the correct direction it would
> be much appreciated.
Ben's right, you can use BitStruct for this:
require 'bit-struct'
class AudioData < BitStruct
unsigned :audio_length, 3*8, :endian => :little
rest :data
# Note: don't use :length as the name of a field, because it will
# conflict with the #length method inherited from String.
# the :endian option can also be :big, :network (== :big), or :native
end
audio_data = AudioData.new
data = "foo bar baz"
audio_data.data = data
audio_data.audio_length = data.length
p audio_data
p audio_data.to_s
__END__
Output:
#<AudioData audio_length=11, data="foo bar baz">
"\v\000\000foo bar baz"
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407