Here is my code. Ideally both struct.unpack and encode('hex') and changing it back to int should be the same right?
INPUT -
But, they are not the same in this case when you give a .wav file with nchannels = 1, samplewidth = 2, framerate = 44100, comptype = "None", compname = "Not compressed"
SAMPLE OUTPUT -
-15638 == eac2 == 27330
-15302 == 3ac4 == 15044
-14905 == c7c5 == 18373
-14449 == 8fc7 == 4039
The left and right hand-side should be equal right?
import wave
import sys
import struct
audiofile = wave.open(sys.argv[1], 'r')
# reading a file (normal file open)
print audiofile.getparams()
# (nchannels, sampwidth, framerate, nframes, comptype, compname)
for i in range(audiofile.getnframes()):
frame = audiofile.readframes(1)
# reading each frame (Here frame is 16 bits [.wav format of each frame])
print struct.unpack('<h', frame)[0], ' == ',
# struct.unpack(fmt, string) --- for more info about fmt -> https://docs.python.org/2/library/struct.html
# If we it is two samples per frame, then we get a tuple with two values -> left and right samples
value = int(frame.encode('hex'), 16)
# getting the 16-bit value [each frame is 16 bits]
if(value > 32767):
value -= 2**16
# because wav file format specifies 2's compliment as in even the negative values are there
print frame.encode('hex') , ' == ', value
audiofile.close()
The difference is between big-endian and little-endian encoding.
Your struct is big-endian, while the conversion with hex is little-endian.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.