这让我头疼了一天,但由于已经弄清楚了,因此我想将其发布在某处,以防它有所帮助。

我正在使用python的wave模块将数据写入wave文件。我不使用scipy.io.wavfile,因为数据可能是一个巨大的矢量(16kHz的音频小时),我不想/无法一次全部加载到内存中。我的理解是scipy.io.wavfile仅提供了完整的文件接口(interface),而wave则允许您在缓冲区中进行读写。如果我错了,我希望对此予以纠正。

我遇到的问题归结为如何将float数据转换为wave.writeframes函数的字节。我的数据写入顺序不正确。这是因为我使用了numpy.getbuffer()函数将数据转换为字节,这不考虑数据的方向:

x0 = np.array([[0,1],[2,3],[4,5]],dtype='int8')
x1 = np.array([[0,2,4],[1,3,5]],dtype='int8').transpose()
if np.array_equal(x0, x1):
    print "Data are equal"
else:
    print "Data are not equal"
b0 = np.getbuffer(x0)
b1 = np.getbuffer(x1)

结果:
Data are equal

In [453]: [b for b in b0]
Out[453]: ['\x00', '\x01', '\x02', '\x03', '\x04', '\x05']

In [454]: [b for b in b1]
Out[454]: ['\x00', '\x02', '\x04', '\x01', '\x03', '\x05']

我假设字节顺序由内存中的初始分配确定,因为numpy.transpose()不会重写数据,而只是返回一个 View 。但是,由于此事实已被numpy数组的接口(interface)所掩盖,因此请在知道这是一个麻烦之前进行调试。

一个解决方案是使用numpy的tostring()函数:
s0 = x0.tostring()
s1 = x1.tostring()
In [455]: s0
Out[455]: '\x00\x01\x02\x03\x04\x05'

In [456]: s1
Out[456]: '\x00\x01\x02\x03\x04\x05'

对于首先说tostring()函数的任何人来说,这可能是显而易见的,但是以某种方式,我的搜索没有找到任何有关如何格式化整个numpy数组以用于wave文件编写的很好的文档,而不是使用scipy.io.wavfile。就是这样。只是为了完成(请注意,“功能”最初是n_channels x n_samples,这就是为什么我要从以下数据顺序问题开始:
outfile = wave.open(output_file, mode='w')
outfile.setnchannels(features.shape[0])
outfile.setframerate(fs)
outfile.setsampwidth(2)
bytes = (features*(2**15-1)).astype('i2').transpose().tostring()
outfile.writeframes(bytes)
outfile.close()

最佳答案

对我来说,tostring可以正常工作。请注意,在WAVE中,必须对8位文件进行签名,而对其他文件(16位或32位)必须进行签名。

一些对我有用的肮脏演示代码:

import wave
import numpy as np

SAMPLERATE=44100
BITWIDTH=8
CHANNELS=2

def gensine(freq, dur):
    t = np.linspace(0, dur, round(dur*SAMPLERATE))
    x = np.sin(2.0*np.pi*freq*t)
    if BITWIDTH==8:
        x = x+abs(min(x))
        x = np.array( np.round( (x/max(x)) * 255) , dtype=np.dtype('<u1'))
    else:
        x = np.array(np.round(x * ((2**(BITWIDTH-1))-1)), dtype=np.dtype('<i%d' % (BITWIDTH/8)))

    return np.repeat(x,CHANNELS).reshape((len(x),CHANNELS))

output_file="test.wav"

outfile = wave.open(output_file, mode='wb')
outfile.setparams((CHANNELS, BITWIDTH/8, SAMPLERATE, 0, 'NONE', 'not compressed'))
outfile.writeframes(gensine(440, 1).tostring())
outfile.writeframes(gensine(880, 1).tostring())
outfile.close()

关于python - 使用wave(不是scipy.io.wavfile)模块将numpy数组写入缓冲区中的wave文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28570370/

10-12 19:23