我必须从Python中的立体声波形文件中的一个通道读取数据.为此我用scipy.io试了一下:
import scipy.io.wavfile as wf
import numpy
def read(path):
data = wf.read(path)
for frame in data[1]:
data = numpy.append(data, frame[0])
return data
Run Code Online (Sandbox Code Playgroud)
但是这段代码非常慢,特别是如果我必须使用更长的文件.那么有人知道更快的方法吗?我通过使用wave.readframes()来考虑标准波形模块,但帧是如何存储的?
War*_*ser 14
scipy.io.wavfile.read返回元组(rate, data).如果文件是立体声,data则是具有形状的numpy数组(nsamples, 2).为了得到一个特定的通道,用切片的data.例如,
rate, data = wavfile.read(path)
# data0 is the data from channel 0.
data0 = data[:, 0]
Run Code Online (Sandbox Code Playgroud)
该wave模块返回帧作为字节串,其可以被转换为数字与struct模块.例如:
def oneChannel(fname, chanIdx):
""" list with specified channel's data from multichannel wave with 16-bit data """
f = wave.open(fname, 'rb')
chans = f.getnchannels()
samps = f.getnframes()
sampwidth = f.getsampwidth()
assert sampwidth == 2
s = f.readframes(samps) #read the all the samples from the file into a byte string
f.close()
unpstr = '<{0}h'.format(samps*chans) #little-endian 16-bit samples
x = list(struct.unpack(unpstr, s)) #convert the byte string into a list of ints
return x[chanIdx::chans] #return the desired channel
Run Code Online (Sandbox Code Playgroud)
如果您的WAV文件有一些其他的样本大小,您可以在另一个答案我写的使用(丑陋)函数在这里.
我从来没有使用scipy的wavfile功能,所以我无法比拟的速度,但wave和struct我在这里使用的方法一直为我工作.