【问题标题】:Read the data of a single channel from a stereo wave file in Python在 Python 中从立体声文件中读取单个通道的数据
【发布时间】:2014-04-18 12:42:26
【问题描述】:

我必须从 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 模块,但帧是如何存储在那里的?

【问题讨论】:

    标签: python scipy wave


    【解决方案1】:

    scipy.io.wavfile.read 返回元组 (rate, data)。如果文件是立体文件,data 是一个形状为(nsamples, 2) 的numpy 数组。要获取特定频道,请使用 slicedata。例如,

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

    【讨论】:

    • 在立体声文件中,“通道”指的是左信号或右信号。即left = data[:, 0]right = data[:, 1]。另见stackoverflow.com/questions/13995936/…
    • 这很好用,但是我如何在不保存为 wav 的情况下传递这个频道到另一个函数?
    • 这取决于其他函数所期望的输入格式。您应该为此创建一个新的 stackoverflow 问题。 cmets 不是解决新问题的地方。
    • 谢谢你,先生,我提出了一个问题——你能调查一下吗? stackoverflow.com/questions/63467345/…
    【解决方案2】:

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

    我从未使用过scipywavfile 函数,因此无法比较速度,但我在这里使用的wavestruct 方法一直对我有用。

    【讨论】:

      【解决方案3】:

      速率,音频 = wavfile.read(path)

      audio = np.mean(audio, axis=1)

      【讨论】:

      • 您能否为您的答案添加一些解释并正确格式化?该问题已有一个可接受的答案。
      • @Elijah:请阅读社区指南以编写好的答案:https://stackoverflow.com/help/how-to-answer
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      相关资源
      最近更新 更多