基于python3下wav文件的时域图和频域图
发布日期:2022/8/23 17:13:48 浏览量:
基于python3下wav文件的时域图和频域图
import wave
import math
import numpy as np
import matplotlib.pyplot as plt
class Audiowave:
def __init__(self,filedir):
self.filedir=filedir
self.wavedata=[]
self.wavewidth=2
self.wavechannel=2
self.framerate = 0
self.Timedata=[]
self.nframes=0
def waveopen(self):
wf=wave.open(self.filedir,"rb")
self.nframes = wf.getnframes()
self.wavedata = wf.readframes(self.nframes)
self.wavewidth=wf.getsampwidth()
self.wavechannel=wf.getnchannels()
self.framerate = wf.getframerate()
time=self.nframes/self.framerate
bps=self.framerate*self.wavewidth*8*self.wavechannel
print("总帧数:"+str(self.nframes)+"帧")
print("采样率:"+str(self.framerate)+"帧/s")
print("声道数:"+str(self.wavechannel)+"个")
print("位深:"+str(self.wavewidth*8)+"bit")
print("比特率:"+str(bps/1000)+"kbps")
print("时间:"+ str(time)+"s")
print("文件大小:"+ str(time*bps/8/1000)+"KB")
return self.wavedata,self.wavewidth,self.wavechannel,self.framerate,time
def wavehex_to_DEC(self,wavedata,wavewidth,wavechannel):
n = int(len(wavedata) / wavewidth)
i = 0
j = 0
for i in range(0, n):
b = 0
for j in range(0, wavewidth):
temp = wavedata[i * wavewidth:(i + 1) * wavewidth][j] * int(math.pow(2, 8 * j))
b += temp
if b > int(math.pow(2, 8 * wavewidth - 1)):
b = b - int(math.pow(2, 8 * wavewidth))
self.Timedata.append(b)
self.Timedata = np.array(self.Timedata)
self.Timedata.shape = -1, wavechannel
self.Timedata = self.Timedata.T
x = np.linspace(0, len(self.Timedata[0]), len(self.Timedata[0])) / self.framerate
return x,self.Timedata
def to_fft(self,data):
N=self.nframes #取样点数
df = self.framerate / (N - 1) # 分辨率
freq = [df * n for n in range(0, N)]
wave_data2 = data[0:N]
c = np.fft.fft(wave_data2) * 2 / N
d = int(len(c) / 2)
freq=freq[:d - 1]
fredata=abs(c[:d - 1])
return freq,fredata
def wavedraw1(self):
self.waveopen()
timedata=self.wavehex_to_DEC(self.wavedata,self.wavewidth,self.wavechannel)
fredata=self.to_fft(timedata[1][0])
plt.figure(figsize=(16, 8))
plt.subplot(2,1,1)
plt.plot(timedata[0], timedata[1][0])
plt.xlabel(u"Time(S)")
plt.subplot(212)
plt.plot(fredata[0],fredata[1])
plt.xlim(0, 800)
plt.xlabel(u"Freq(Hz)")
plt.subplots_adjust(hspace=0.4)
plt.show()
def wavedrawall(self):
self.waveopen()
n=self.wavechannel
timedata = self.wavehex_to_DEC(self.wavedata, self.wavewidth, self.wavechannel)
xtimedata=timedata[0]
ytimedata=timedata[1]
# print(ytimedata)
i=0
plt.figure(figsize=(16, 8))
# plt.legend(prop=font_set)
for i in range(0,n):
a=plt.subplot(2, n, i+1)
a.set_title("track"+str(i+1))
plt.plot(xtimedata, ytimedata[i])
plt.xlabel(u"Time(S)")
# print(ytimedata[i])
fredata = self.to_fft(ytimedata[i])
plt.subplot(2,n,i+1+n)
plt.plot(fredata[0], fredata[1])
plt.xlim(0, 4000)
plt.xlabel(u"Freq(Hz)")
plt.subplots_adjust(hspace=0.4)
plt.show()
# a=Audiowave("file.wav").wavedraw1()
a=Audiowave(r"1.wav").wavedrawall()
业务实施流程
马上咨询: 如果您有业务方面的问题或者需求,欢迎您咨询!我们带来的不仅仅是技术,还有行业经验积累。
QQ: 39764417/308460098 Phone: 13 9800 1 9844 / 135 6887 9550 联系人:石先生/雷先生