[英]Power spectrum of wav file using python
我試圖加載波形文件並使用傅立葉變換打印其頻譜。 我遵循了我找到的書並從那里得到了一些代碼,但是結果有點不同。
def read_wave(filename):
fp=wave.open(filename,'r')
nchannels=fp.getnchannels()
framerate=fp.getframerate()
nframes=fp.getnframes()
sampwidth=fp.getsampwidth()
z_str=fp.readframes(nframes)
fp.close()
dtype_map={1:np.uint8,2:np.uint16}
ys=np.frombuffer(z_str,dtype=dtype_map[sampwidth])
waveObject=Wave(ys,framerate=framerate)
return waveObject
class Wave:
def __init__(self,ys,ts=None,framerate=None):
# ys:wave array
# ts:array of time
self.ys=np.asanyarray(ys)
self.framerate=framerate
if ts is None:
self.ts =np.arange(len(ys))/self.framerate
else:
self.ts=ts
def make_spectrum(self):
n=len(self.ys);
d=1/self.framerate;
hs = np.fft.rfft(self.ys)
fs = np.fft.rfftfreq(n, d)
return Spectrum(hs,fs,self.framerate)
class Spectrum:
def __init__(self,hs,fs,framerate):
# hs : array of amplitudes (real or complex)
# fs : array of frequencies
self.hs=np.asanyarray(hs)
self.fs=np.asanyarray(fs)
self.framerate=framerate
@property
def amps(self):
return np.absolute(self.hs)
def plot(self, high=None):
plt.plot(self.fs, self.amps)
data=read_wave('hate.wav') <br>
spectrum=data.make_spectrum()<br>
spectrum.plot()<br>
但是我得到的頻譜看起來像這樣,看起來不正確,有什么幫助嗎?
在f = 0處有一個巨大的峰值,這表明信號具有恆定的偏移量。
它可能與使用無符號整數類型有關:
dtype_map={1:np.uint8,2:np.uint16}
嘗試使用帶符號的類型,或從信號中減去平均值以消除偏移。
WAVE文件中存儲的無符號8位樣本的范圍為0到255,因此具有DC偏移。 您的FFT在一開始就顯示此DC偏移具有巨大的尖峰。 從每個樣本中減去DC偏移(應為128,或者由於記錄錯誤而導致的某個值大約為128)將消除FFT中巨大的DC偏移尖峰,並允許圖自動縮放以更好地顯示其他頻率段。
WAVE文件中的16位樣本為有符號整數格式,因此將其讀取為無符號值可能會破壞數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.