如何在python中使用struct module将16位ASCII数据解码为一个由2个字符组成的字符串?

2024-10-06 11:51:30 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码。理想情况下两者都有解包结构和encode('hex')并将其改回int应该是相同的对吗?

输入-

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"

样本输出-

-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()

Tags: theinimportrightisvalueframestruct