[英]How to convert from string to 16-bit unsigned integer in python?
[英]How to decode a 16-bit ASCII data to an integer when you have it in a string of 2 characters in python using struct module?
這是我的代碼。 理想情況下,struct.unpack和encode('hex')都將其更改回int應該是正確的嗎?
輸入-
但是,當您給一個.wav文件提供nchannels = 1,samplewidth = 2,framerate = 44100,comptype =“ None”,compname =“ Not Compressed”時,它們是不一樣的
樣品輸出-
-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()
大端和小端編碼之間的區別。
您的結構是big-endian,而十六進制的轉換是little-endian。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.