My goal is to overwrite the wav extension file into a binary file (binary file / file.bin). For coding, I use quantization theory (creating a quantization step ....).

The code implements the encoding function. The elements that change are the track itself, the number of bits and the target (that is, in which file I write, in my case it is bin).

import scipy.io.wavfile as wav import numpy as np import pickle def enc(track, n, target): rate, data = wav.read(track) qStep = (float(np.max(data)) - float(np.min(data)))/(2**n-1) dataQuant = np.round(data/(qStep))*qStep b = open(target, 'wb') pickle.dump(data, b, pickle.HIGHEST_PROTOCOL) b.close() 

If I run it as: enc('track.wav', 16, 'enс.bin') . I get a binary file that is similar in size with the track, which I think is true, since the track is 16 bits.

If I run: enc('track.wav', 8, 'enс8.bin') , i.e. if I want to transcode to 8 bits, I get a file that is similar in size to en. Bin, although it should be 2 times smaller than size.

I use the same track.

How do I fix my mistake?

New task

I want to overwrite my file back, that is, from the bin format to wav. For this I prescribe:

 b = open(filename,"rb") data= pickle.load(b) b.close() scipy.io.wavfile.write(str.replace(filename,".bin","_decoded.wav"), 44100, data) 

I get a "terrible" track when decoding from 8 bits of a file. How to fix?

  • You can talk about an error only if the files are not "similar" in size, but exactly the same ... Do you have to create files again every time? - Vladimir Martyanov
  • @ Vladimir Martianov, for the function I use the same track (16 bits) and encode it in 16 bits or 8 bits file. When coding in 8 bits, a binary file (binary file / enc.bin) should create a file less than 16 bits - LenaPark
  • @LenaPark and the file is created in how many bytes? Only not "it seems", but for sure Maybe there is no error? - Vladimir Martyanov
  • @ Vladimir Martianov, my file is 4.7 mb in size, exactly like the size of the track. Track 4, 7 mb and 16 bits, if I recode it to 8 bits, shouldn't the 8-bit file be smaller? - LenaPark
  • @ Vladimir Martiyanov, what he owed less, already checked. Using ' scaled =np.array(data/255,dtype='int8') - LenaPark

1 answer 1

Try this:

 ... qStep = (float(np.max(data)) - float(np.min(data)))/(2**(n-1)) precision = n // 8 * 8 dataQuant = np.array(np.round(data/(qStep))*qStep, dtype='int{}'.format(precision)) b = open(target, 'wb') pickle.dump(dataQuant, b, pickle.HIGHEST_PROTOCOL) ... 
  • What does your line precision = n // 8 * 8 mean? - LenaPark