Python 频谱分析核心代码

Python 3.5
Dependence:numpy,scipy,matplotlib,wave

import numpy as np
from scipy import signal
import matplotlib.pylab as plt
import wave
import matplotlib.animation as animation

f=wave.open(r".\demo.wav","rb")
params = f.getparams()  
nchannels, sampwidth, framerate, nframes = params[:4]
str_data  = f.readframes(nframes)  
f.close()
wave_data = np.fromstring(str_data,dtype = np.short)  
wave_data.shape = -1,2  
wave_data = wave_data.T  
time = np.arange(0,nframes)*(1.0/framerate) 


'''
    至此音频信号已转换为序列
    wave_data 音频信号序列
    time 时间序列(sec)
    framerate 采样率(Hz)
    nchannels 信道数量
'''


fig = plt.figure() 
axes1 = fig.add_subplot(111)
fs=framerate
dat=wave_data[0]/65536.0
intervals=0.05 #second
divide=256
index=0
f, Pwelch_spec = signal.welch(dat[index:index+divide], fs,scaling='spectrum')
line, = axes1.plot(f,Pwelch_spec)
axes1.set_ylabel('dB')
axes1.set_xlabel('f (Hz)')
def update(data): 
    line.set_ydata(data)
    ymin,ymax=axes1.get_ylim()
    axes1.set_ylim(-20,0)
    axes1.set_xlim(np.min(f),np.max(f))
    axes1.figure.canvas.draw()
    return line, 
def data_gen():
    global index
    while (index+divide<nframes): 
        f,_ = pwelch_spec=signal.welch(dat[index:index+divide], fs,scaling="spectrum" )
        yield f
animation.FuncAnimation(fig,update,data_gen,interval=50)
plt.show()


评论

发表回复