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

Ric*_*pen 4 python scipy wave

我必须从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)

  • 在立体声文件中,“声道”指的是左信号或右信号。即,`left = data[:, 0]`,`right = data[:, 1]`。另见 http://stackoverflow.com/questions/13995936/what-is-a-channel-in-a-wav-file-formatdo-all-channels-play-simultaneaously-whe (2认同)

mtr*_*trw 6

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文件有一些其他的样本大小,您可以在另一个答案我写的使用(丑陋)函数在这里.

我从来没有使用scipywavfile功能,所以我无法比拟的速度,但wavestruct我在这里使用的方法一直为我工作.