问题描述
我有一些 wav 文件.我想使用 SciPy FFT 来绘制这些 wav 文件的频谱.我该怎么做?
I have a handful of wav files. I'd like to use SciPy FFT to plot the frequency spectrum of these wav files. How would I go about doing this?
推荐答案
Python
提供了几个 api 来相当快地做到这一点.我从 这个链接 下载了羊叫声 wav 文件.您可以将它保存在桌面上,然后在终端内 cd
那里.python
提示中的这些行应该足够了:(省略 >>>>
)
Python
provides several api to do this fairly quickly. I download the sheep-bleats wav file from this link. You can save it on the desktop and cd
there within terminal. These lines in the python
prompt should be enough: (omit >>>
)
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.io import wavfile # get the api
fs, data = wavfile.read('test.wav') # load the data
a = data.T[0] # this is a two channel soundtrack, I get the first track
b=[(ele/2**8.)*2-1 for ele in a] # this is 8-bit track, b is now normalized on [-1,1)
c = fft(b) # calculate fourier transform (complex numbers list)
d = len(c)/2 # you only need half of the fft list (real signal symmetry)
plt.plot(abs(c[:(d-1)]),'r')
plt.show()
这是输入信号的绘图:
Here is a plot for the input signal:
这是光谱
为了获得正确的输出,您必须将 xlabel
转换为频谱图的频率.
For the correct output, you will have to convert the xlabel
to the frequency for the spectrum plot.
k = arange(len(data))
T = len(data)/fs # where fs is the sampling frequency
frqLabel = k/T
如果你必须处理一堆文件,你可以把它作为一个函数来实现:将这些行放在 test2.py
中:
If you are have to deal with a bunch of files, you can implement this as a function:put these lines in the test2.py
:
import matplotlib.pyplot as plt
from scipy.io import wavfile # get the api
from scipy.fftpack import fft
from pylab import *
def f(filename):
fs, data = wavfile.read(filename) # load the data
a = data.T[0] # this is a two channel soundtrack, I get the first track
b=[(ele/2**8.)*2-1 for ele in a] # this is 8-bit track, b is now normalized on [-1,1)
c = fft(b) # create a list of complex number
d = len(c)/2 # you only need half of the fft list
plt.plot(abs(c[:(d-1)]),'r')
savefig(filename+'.png',bbox_inches='tight')
说,我当前工作目录下有test.wav
和test2.wav
,python
提示界面下面的命令就够了:导入测试2地图(test2.f, ['test.wav','test2.wav'])
Say, I have test.wav
and test2.wav
in the current working dir, the following command in python
prompt interface is sufficient: import test2 map(test2.f, ['test.wav','test2.wav'])
假设你有 100 个这样的文件并且你不想单独输入它们的名字,你需要 glob
包:
Assuming you have 100 such files and you do not want to type their names individually, you need the glob
package:
import glob
import test2
files = glob.glob('./*.wav')
for ele in files:
f(ele)
quit()
如果您的 .wav 文件不是同一位,您将需要在 test2.f 中添加 getparams
.
这篇关于Python Scipy FFT wav 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!