【问题标题】:wav file amplitude calculationswav 文件幅度计算
【发布时间】:2014-03-09 00:44:00
【问题描述】:

我正在用正弦波读取并在 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)
  • 你的问题是什么?
  • tom10,修复了它。在此过程中,我还修复了一些其他错误。
  • @The_Glidd:很好。我发布了一个答案来结束这个问题。如果需要其他任何通常有用的东西,您可以将其添加到我的答案中。

标签: python audio numpy


【解决方案1】:

默认情况下,astype 不会就地完成,而是使用:

byteList = byteList.astype(np.float)

在某些情况下,astype 可以在关键字 copy=True 时就地完成(参见文档),但即使就地完成,它也会返回数组,因此可以使用上述形式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多