How to save a string of 1's and 0's as binary to a binary file in Python

226 Views Asked by At

I am currently trying to complete a project for school that involves reading an audio 'wav' file, using a golomb encoder to encode the samples, writing the result to a binary file, reading that binary file on another script and decoding it using the golomb decoder. The assignment guide suggests I develop a BitStream class that can read and write a single bit and read and write n bits. I have done the golomb encoder and decoder and it seems to be working well. However, I am having trouble with the BitStream part. I have tried searching for existing classes online but as I am fairly new to programming, they all seem super complicated to work with. My golomb coder returns a string of 1's and 0's and the decoder works with a similar string as input. Another questions I have are: When I am done writing the binary files, how do I know where each sample code starts and ends? How do I pass the sampling frequency to the decoder? How do I know where the left and right channels of the audio sample begin and end? How do I encode the M parameter of the golomb encoder of each separate sample? I am supposed to do this in Python by the way.

Thanks in advance!

1

There are 1 best solutions below

0
oppressionslayer On

Once you have the binary, you shouldn't have to worry about where the audio starts, etc, the libraries should do that for you. To save a string with bitstring you can do them all at once, save to a string then run the BitStream like:

BitStream(bin='101010101').tofile(filename)  

Your question has a few moving parts, but if your string of one zeroes is working with golomb, the binary you read back from BitString should work as is.

One tip i have, i use this for huffman encoders too. If the binary strings you generate with the encode you have ever start with '0000's Then always prepend a '1' to the binary string before write, and strip the prepended '1' on read. This keeps you from having to store an external data about the save of the binary buffer, since binary has to be stored with a leading 1