在Python中从立体声波文件读取单个通道的数据

2024-05-19 05:07:30 发布

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

我只能从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

但这段代码非常慢,特别是如果我必须处理较长的文件。 有人知道更快的方法吗?我通过使用wave.readframes()考虑了标准的wave模块,但是这些帧是如何存储的呢?


Tags: 文件pathioimportnumpyreaddataas
3条回答

^{}返回元组(rate, data)。如果文件是立体的,data是具有形状(nsamples, 2)的numpy数组。若要获取特定通道,请使用dataslice。例如

rate, data = wavfile.read(path)
# data0 is the data from channel 0.
data0 = data[:, 0]

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

如果你的WAV文件有其他的样本大小,你可以在我写的另一个答案here中使用(更丑的)函数。

我从来没有使用过scipywavfile函数,所以我无法比较速度,但是我在这里使用的wavestruct方法对我一直都很有效。

rate,audio=wavfile.read(路径)

音频=np.平均值(音频,轴=1)

相关问题 更多 >

    热门问题