所以我问了标题中的所有内容:
我有一个 wav 文件(由 PyAudio 从输入音频编写),我想将其转换为与声级(振幅)相对应的浮点数据,以进行一些傅里叶变换等...
有人有将 WAV 数据转换为 float 的想法吗?
我已经找到了两种不错的方法来做到这一点。
方法一:使用wavefile模块
如果您不介意安装一些额外的库,请使用此方法,这些库在我的 Mac 上会有点麻烦,但在我的 Ubuntu 服务器上很容易。
https://github.com/vokimon/python-wavefile
import wavefile
# returns the contents of the wav file as a double precision float array
def wav_to_floats(filename = 'file1.wav'):
w = wavefile.load(filename)
return w[1][0]
signal = wav_to_floats(sys.argv[1])
print "read "+str(len(signal))+" frames"
print "in the range "+str(min(signal))+" to "+str(max(signal))
方法二:使用wave模块
如果您希望减少模块安装的麻烦,请使用此方法。
从文件系统读取 wav 文件并将其转换为 -1 到 1 范围内的浮点数。它适用于 16 位文件,如果它们 > 1 个通道,将以与在文件中找到的相同方式交错样本。对于其他位深度,请根据本页底部的表更改 struct.unpack 参数中的“h”:
https://docs.python.org/2/library/struct.html
它不适用于 24 位文件,因为没有 24 位数据类型,因此无法告诉 struct.unpack 做什么。
import wave
import struct
import sys
def wav_to_floats(wave_file):
w = wave.open(wave_file)
astr = w.readframes(w.getnframes())
# convert binary chunks to short
a = struct.unpack("%ih" % (w.getnframes()* w.getnchannels()), astr)
a = [float(val) / pow(2, 15) for val in a]
return a
# read the wav file specified as first command line arg
signal = wav_to_floats(sys.argv[1])
print "read "+str(len(signal))+" frames"
print "in the range "+str(min(signal))+" to "+str(max(signal))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)