简体   繁体   English

WAV文件幅度计算

[英]wav file amplitude calculations

I'm messing around with reading in a sine wave and performing some calculations in Python. 我正忙着阅读正弦波并在Python中执行一些计算。 I wonder, though, if the data types established in numpy are causing any trouble. 但是,我不知道numpy中建立的数据类型是否会引起任何麻烦。 My main goal here is to read in a .wav file and find amplitudes for samples. 我的主要目标是读取.wav文件并查找样本的幅度。 I'd rather not use a command line tool like sax or ffmpeg: 我宁愿不使用像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           

By default, astype is not done in-place, instead use: 默认情况下, astype不是就地完成的,而是使用:

byteList = byteList.astype(np.float)

In some situations, astype can be done in-place (see the docs) when keyword copy=True , but even when done in-place, it returns the array, so the above form can be used. 在某些情况下,当关键字copy=True时, astype可以就地完成(请参阅文档),但是即使就地完成,它也会返回数组,因此可以使用上述形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM