這是我的代碼。 理想情況下,struct.unpack和encode('hex')並將其更改回int應該是相同的權利?如何解碼一個16位ASCII數據爲一個整數,當你在Python中使用結構模塊中的2個字符的字符串?
INPUT -
但是,他們不在這種情況下,同樣的,當你給用nchannels = 1,samplewidth = 2 .wav文件,幀率= 44100,comptype = 「無」 ,COMPNAME = 「未壓縮」
樣本輸出 -
-15638 == eac2 == 27330
-15302 == 3ac4 == 15044
-14905 == c7c5 == 18373
-14449 == 8fc7 == 4039
的左手和右手側應等於對?
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()
你的縮進似乎有問題。請修復? – smarx
也不確定你的問題是什麼。也許你可以給一小段代碼,分享它的輸出,並分享你所期望的輸出。 – smarx
@smarx我已經添加了一個示例輸出。我的主要問題是如果我將幀編碼爲十六進制並將其轉換回int類型,並且如果我使用結構模塊直接獲取int類型的16位值 - 它們應該相等嗎? –