簡體   English   中英

WAV文件幅度計算

[英]wav file amplitude calculations

我正忙着閱讀正弦波並在Python中執行一些計算。 但是,我不知道numpy中建立的數據類型是否會引起任何麻煩。 我的主要目標是讀取.wav文件並查找樣本的幅度。 我寧願不使用像sax或ffmpeg這樣的命令行工具:

f = wave.open('sine.wav','rb') #3 second long sine wav

nchannels, sampwidth, framerate, nframes, comptype, compname = f.getparams()[:6]

if sampwidth != 2:
    raise ValueError("Only supports 16 bit audio formats")

if nchannels == 2:
    nframes*=2 #this seems to give me all data when I read in a 2-channel wave

byteList = np.fromstring(f.readframes(nframes), dtype = np.int16)

f.close()

byteList.astype(float) #attempt to change type to perform the following operations

maximum = max(byteList)
minimum = min(byteList)
peak = (abs(maximum)+abs(minimum))/2) #find a good max amplitude.  This fails 
    #RuntimeWarning: overflow encountered in short_scalars.  I thought I changed type! 

#I check to see the indices where the max amplitude occurs.  I get no results.
for i in byteList[0:nframes]:
    if peak <= (byteList[i]):
        print('These are the indices where the maximum occurs: {}'.format(i))

#Find the rms value.  This gets me .7344... Close, I guess.
total = 0
for i in byteList[0:nframes]:
    total+=(((byteList[i])/peak))**2
rms = math.sqrt(total/nframes)
print('This is rms: {}'.format(rms))


#Here I tree to find the max amplitude every second.  I get an empy list.  
i = 0
j = 1
amp_list = [0] #default max
while (i < nframes):
    for i in byteList[i:j*framerate]:
        if byteList[i+1] >= byteList[i]:
            amp_list.pop()
            amp_list.append(byteList[i+1])
    j+=1
    i+=framerate           

默認情況下, astype不是就地完成的,而是使用:

byteList = byteList.astype(np.float)

在某些情況下,當關鍵字copy=True時, astype可以就地完成(請參閱文檔),但是即使就地完成,它也會返回數組,因此可以使用上述形式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM