python 实现wav的波形显示(时域和频域)

  音频处理中,经常要看一下啊频域图是什么样子的,这里自己写了一个小程序,可以完美的同步显示时域和频域图,直接上代码:

 1 #wave data   -xlxw
 2 
 3 #import
 4 import wave as we
 5 import numpy as np
 6 import matplotlib.pyplot as plt 
 7 import sys 
 8 
 9 def wavread(path):
10     wavfile =  we.open(path,"rb")
11     params = wavfile.getparams()
12     framesra,frameswav= params[2],params[3]
13     nchannels, sampwidth, framesra, frameswav = params[:4]
14     print("nchannels:%d" % nchannels)
15     print("sampwidth:%d" % sampwidth)
16     datawav = wavfile.readframes(frameswav)
17     wavfile.close()
18     datause = np.fromstring(datawav,dtype = np.short)
19     print(len(datause))
20     if nchannels == 2:
21         datause.shape = -1,2
22     datause = datause.T
23     time = np.arange(0, frameswav) * (1.0/framesra)
24     return datause,time,nchannels
25 
26 def main():
27     path = sys.argv[1]
28     #path = input("The Path is:")
29     print(path)
30     wavdata,wavtime,nchannels = wavread(path)
31         
32     N=len(wavdata)
33     framerate = 16000
34     start=0 
35     df = 1 
36     freq = [df*n for n in range(0,len(wavdata))] 
37     print(len(wavdata))
38     print(len(wavtime))
39         
40     c=np.fft.fft(wavdata)*nchannels
41     d=int(len(c)/2)
42     print(len(c))
43 
44     fig, ax = plt.subplots(2, 1)
45 
46 
47     ax[0].plot(wavtime,wavdata,color = 'green')
48     ax[0].set_xlabel('Time')
49     ax[0].set_ylabel('Amplitude')
50 
51 
52     ax[1].plot(freq,abs(c),color = 'red')
53     ax[1].set_xlabel('Freq(HZ)')
54     ax[1].set_ylabel('Y(freq)')
55         
56     plt.show()

 直接上图看结果:

python 实现wav的波形显示(时域和频域)_第1张图片

   这个只能对单声道16k采样的wav格式做处理,不过,只要稍微加一更改,就可以处理别的了。具体改代码的事情,还是谁用谁做吧。做个程序员,总要付出一些代价的。

每日一言:君子役物,小人役于物。——《劝学》

转载于:https://www.cnblogs.com/dylancao/p/9783410.html

你可能感兴趣的:(python 实现wav的波形显示(时域和频域))