5

我得到了一个连续水下记录的大型 WAV 文件,我想将其转换为 numpy 数组进行分析。我正在努力做到这一点。

到目前为止,我有:

import numpy as np
import scipy as sp
import wave as wv
import struct

wavefile = wv.open(filename,'r')
(nchannels,sampwidth,framerate,nframes,comptype,compname) = wavefile.getparams()

// read a sample as example

wavedata =wavefile.readframes(1)

第一帧如下所示:'\xcd\xbc\xff@\x01\x00'。我尝试使用 struct 解压它,但无论我做什么都解压我得到以下错误:“ str size does not match format ”。我想这与 Python struct 无法处理 24 位数据有关。

波形文件的参数如下所示:

  • nchannels=2
  • 采样宽度=3
  • 帧率=48000
  • nframes=283516532L
  • comptype='无'
  • compname='未压缩'

有人知道如何将 24 位立体声 WAV 文件读入 numpy 数组吗?

4

3 回答 3

6

这是一个处理具有任意数量通道的 2、3 和 4 字节 WAV 文件的循环:

def dataFromWave(fname):
""" return list with interleaved samples """
    f = wave.open(fname, 'rb')
    chans = f.getnchannels()
    samps = f.getnframes()
    sampwidth = f.getsampwidth()
    if  sampwidth == 3: #have to read this one sample at a time
        s = ''
        for k in xrange(samps):
            fr = f.readframes(1)
            for c in xrange(0,3*chans,3):                
                s += '\0'+fr[c:(c+3)] # put TRAILING 0 to make 32-bit (file is little-endian)
    else:
        s = f.readframes(samps)
    f.close()
    unpstr = '<{0}{1}'.format(samps*chans, {1:'b',2:'h',3:'i',4:'i',8:'q'}[sampwidth])
    x = list(struct.unpack(unpstr, s))
    if sampwidth == 3:
        x = [k >> 8 for k in x] #downshift to get +/- 2^24 with sign extension
    return x
于 2013-11-15T11:03:52.787 回答
2

对于那些有类似问题的人,我发布了我的解决方案。请注意,这会将 24 位波形文件转换为有符号浮点 numpy 数组。仅在转换为整数时将 /int2float 部分排除在外。

frames = wavfile.readframes(nsamples)

ch1 = np.zeros(nsamples)
ch2 = np.zeros(nsamples)
int2float = (2**23)-1

for x in np.arange(int(nsamples)):
    ch1_24bit_sample = frames[x*6:x*6+3]
    ch2_24bit_sample = frames[x*6+3:x*6+6]
    ch1_32bit_sample = bit24_2_32(ch1_24bit_sample)
    ch2_32bit_sample = bit24_2_32(ch2_24bit_sample)
    ch1[x]=struct.unpack('i',ch_32bit_sample)[0]
    ch2[x]=struct.unpack('i',ch_32bit_sample)[0]
    ch1[x]=ch1[x]/int2float
    ch2[x]=ch2[x]/int2float

def bit24_2_32(strbytes):
    if strbytes[2] < '\x80':
       return strbytes+'\x00'
    else:
       return strbytes+'\xff'
于 2013-11-15T10:46:58.327 回答
1

这是一个老问题,但如果有人需要其他选项并且对使用外部模块没有限制,那么您可能可以使用librosa

myNdArray = librosa.core.load(wav_path, sr=sample_rate)[0]
于 2018-05-03T14:13:25.637 回答