Scipy: Trying to write wav file, AttributeError: 'list' object has no attribute 'dtype'

Scipy: Trying to write wav file, AttributeError: 'list' object has no attribute 'dtype'

我正在使用 Anaconda3 和 SciPy 尝试使用数组编写 wav 文件:

wavfile.write("/Users/Me/Desktop/C.wav", 1000, array)

(我不知道每秒有多少样本,我打算试试看,不过我打赌是 1000)

array returns 一个包含 3000 个整数的数组,因此该文件将持续 3 秒。

但是在尝试 运行:

时它给了我这个错误
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-ce3a8d3e4b4b> in <module>()
----> 1 wavfile.write("/Users/Me/Desktop/C.wav", 1000, fin)

/Users/Me/anaconda/lib/python3.4/site-packages/scipy/io/wavfile.py in write(filename, rate, data)
213 
214     try:
--> 215         dkind = data.dtype.kind
216         if not (dkind == 'i' or dkind == 'f' or (dkind == 'u' and data.dtype.itemsize == 1)):
217             raise ValueError("Unsupported data type '%s'" %         data.dtype)

AttributeError: 'list' object has no attribute 'dtype'

您正在传递 write 一个普通的 python 列表,它没有名为 dtype 的属性(您可以通过研究错误消息获得该信息)。 scipy.io.wavfile 的文档明确指出你应该传递一个 numpy 数组:

Definition: wavfile.write(filename, rate, data)

Docstring:

Write a numpy array as a WAV file

您可以将普通的 python 列表转换为 numpy 数组,如下所示:

import numpy as np
arr = np.array(array)

我想补充一些信息来回复 user3151828 的评论。我打开了一个由 32 位带符号浮点值组成的文件,音频数据未格式化为适当的 wave 文件,并创建了一个普通的 Python 列表,然后将其转换为一个 numpy 数组,如 Oliver W. 所述,并打印了结果。

import numpy as np
import os
import struct
file = open('audio.npa', 'rb')
i = 0
datalist = []
for i in range(4):
    data = file.read(4)
    s = struct.unpack('f', data)
    datalist.append(s)
numpyarray = np.array(datalist)
print('datalist, normal python array is: ', datalist, '/n')
print('numpyarray is: ', numpyarray)

输出为:

datalist, normal python list is:  [(-0.000152587890625,), (-0.005126953125,), (-0.010284423828125,), (-0.009796142578125,)]

numpyarray is:
[[-0.00015259]
[-0.00512695]
[-0.01028442]
[-0.00979614]]

所以,两者是有区别的