如何将波形文件转换为浮动幅度

use*_*673 7 python audio wave pyaudio

所以我问标题中的所有内容:

我有一个波形文件(由输入音频的PyAudio编写),我想将其转换为与声级(振幅)相对应的浮点数据,以进行一些傅立叶变换等...

任何人都有想法将WAVE数据转换为浮点数?

yee*_*ing 10

我已经确定了两种不错的方法.

方法1:使用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(min(signal))
Run Code Online (Sandbox Code Playgroud)

方法2:使用波形模块

如果您想减少模块安装麻烦,请使用此方法.

从文件系统读取一个wav文件,并将其转换为-1到1范围内的浮点数.它适用于16位文件,如果它们是> 1通道,将按照它们在文件中找到的相同方式交错采样.对于其他位深度,请根据本页底部的表将参数中的'h'更改为struct.unpack:

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(min(signal))
Run Code Online (Sandbox Code Playgroud)


小智 6

我花了好几个小时试图找到答案.解决方案结果非常简单:struct.unpack是您正在寻找的.最终的代码看起来像这样:

rawdata=stream.read()                  # The raw PCM data in need of conversion
from struct import unpack              # Import unpack -- this is what does the conversion
npts=len(rawdata)                      # Number of data points to be converted
formatstr='%ih' % npts                 # The format to convert the data; use '%iB' for unsigned PCM
int_data=unpack(formatstr,rawdata)     # Convert from raw PCM to integer tuple
Run Code Online (Sandbox Code Playgroud)

大部分功劳归功于解释WAV数据.唯一的技巧是使格式正确解压缩:它必须是正确的字节数和正确的格式(有符号或无符号).


dec*_*jau 5

大多数波形文件采用PCM 16位整数格式.

你想要的是什么:

  • 将标头解析为已知的格式(检查来自Xophmeister的链接)
  • 读取数据,取整数值并将它们转换为float

整数值的范围为-32768到32767,您需要在浮点中将值从-1.0转换为1.0.

我没有python中的代码,但是在C++中,如果PCM数据是16位整数,这里是代码摘录,并将其转换为float(32位):

short* pBuffer = (short*)pReadBuffer;

const float ONEOVERSHORTMAX = 3.0517578125e-5f; // 1/32768 
unsigned int uFrameRead = dwRead / m_fmt.Format.nBlockAlign;

for ( unsigned int i = 0; i < uFrameCount * m_fmt.Format.nChannels; ++i )
{
    short i16In = pBuffer[i];
    out_pBuffer[i] = (float)i16In * ONEOVERSHORTMAX;
}
Run Code Online (Sandbox Code Playgroud)

小心立体声文件,因为波形文件中的立体声PCM数据是交错的,这意味着数据看起来像LRLRLRLRLRLRLRLR(而不是LLLLLLLLRRRRRRRR).根据您对数据的处理方式,您可能需要也可能不需要解交错.


Xop*_*ter -3

Microsoft WAVE 格式有相当详细的文档记录。例如,请参阅https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ 。编写一个文件解析器来打开和解释数据以获得您需要的信息并不需要太多...也就是说,几乎可以肯定以前已经完成过,所以我确信有人会给出一个“更简单”的答案; )