使用python绘制wav 音频文件频谱图
1.wav 文件需要是Windows PCM 格式(未压缩),
2.python 库的安装:
pip install pyaudio(可能会用到)
pip install matplotlib(必需)
pip install scipy(可能会用到)
3. 可以看一下,这里读取出来的有通道数,采样率,采样数等信息,和cool edit 显示的信息是一致
cool edit显示的文件信息,里面显示文件是PCM格式(在《信号与系统》的课里面我们应该学过的哈):
与cool edit显示的频谱图也是一致的:
4. 接下来是最后比较激动的python代码部分(仅供参考),大家可以用wav文件试一下,绘制一下频谱图:
import wave import struct,numpy from scipy import * from pylab import * def Plot_fft_freq_chart(filename,plot=False): wavefile = wave.open(filename, r) # open for writing nchannels = wavefile.getnchannels() sample_width = wavefile.getsampwidth() framerate = wavefile.getframerate() numframes = wavefile.getnframes() print("channel",nchannels) print("sample_width",sample_width) print("framerate",framerate) print("numframes",numframes) y = numpy.zeros(numframes) for i in range(numframes): val = wavefile.readframes(1) left = val[0:2] #right = val[2:4] v = struct.unpack(h, left )[0] y[i] = v Fs = framerate try: data, freqs, bins, im = specgram(y, NFFT=1024, Fs=Fs, noverlap=900) mm=data[127] mm=10. * np.log10(mm+1e-4) except Exception as e: print("error is: ",e) return -50 freq1khz_value=mean(mm) print(freq1khz_value) if plot: show() return freq1khz_value filename1="20-20k.wav" Plot_fft_freq_chart(filename1,True)