我需要从 24 位 pcm 格式的 wav 文件中读取数据,并将其转换为 float 。我正在使用 Python 2.7.2。
wave 包以字符串形式读取数据,所以我尝试过的是:
import wave
import numpy as np
import array
import struct
f = wave.open('filename.wav')
# read in entire wav file
wdata = f.readframes(nFrames)
f.close()
# unpack into signed integers and convert to float
data = array.array('f')
for i in range(0,nFrames*3,3):
data.append(float(struct.unpack('<i', '\x00'+ wdata[i:i+3])[0]))
# normalize sample values
data = np.array(data)
data = data / 0x800000
这比我之前的方法快了很多,但仍然很慢。谁能建议更有效的方法?
请您参考如下方法:
这看起来相当快,它处理 24 位值,并进行规范化:
from scikits.audiolab import Sndfile
import numpy as np
f = Sndfile(fname, 'r')
data = np.array(f.read_frames(f.nframes), dtype=np.float64)
f.close()
return data
