我对python很熟悉,但对numpy很熟悉,所以如果我错了,请原谅我。
我正在尝试读取具有多个频率的.wav文件(由静音分隔)。到目前为止,我已经能够读取值并找到文件中存在声音的各个部分。然后,我试图找到离散余弦变换并从中计算出频率(参考:how to extract frequency associated with fft values in python)
但是,我收到了错误:
索引46392超出轴0的大小为25
这是我的代码:
import wave
import struct
import numpy as np
def isSilence(windowPosition):
sumVal = sum( [ x*x for x in sound[windowPosition:windowPosition+windowSize+1] ] )
avg = sumVal/(windowSize)
if avg <= 0.0001:
return True
else:
return False
#read from wav file
sound_file = wave.open('test.wav', 'r')
file_length = sound_file.getnframes()
data = sound_file.readframes(file_length)
sound_file.close()
#data = struct.unpack("<h", data)
data = struct.unpack('{n}h'.format(n=file_length), data)
sound = np.array(data)
#sound is now a list of values
#detect silence and notes
i=0
windowSize = 2205
windowPosition = 0
listOfLists = []
listOfLists.append([])
maxVal = len(sound) - windowSize
while True:
if windowPosition >= maxVal:
break
if not isSilence(windowPosition):
while not isSilence(windowPosition):
listOfLists[i].append(sound[windowPosition:windowPosition+ windowSize+1])
windowPosition += windowSize
listOfLists.append([]) #empty list
i += 1
windowPosition += windowSize
frequencies = []
#Calculating the frequency of each detected note by using DFT
for signal in listOfLists:
if not signal:
break
w = np.fft.fft(signal)
freqs = np.fft.fftfreq(len(w))
l = len(signal)
#imax = index of first peak in w
imax = np.argmax(np.abs(w))
fs = freqs[imax]
freq = imax*fs/l
frequencies.append(freq)
print frequencies
编辑:这是追溯:
Traceback (most recent call last):
File "final.py", line 61, in <module>
fs = freqs[imax]
IndexError: index 46392 is out of bounds for axis 0 with size 21
答案 0 :(得分:0)
问题是我假设listOfLists
实际上是一个列表列表,但实际上它是一个列表列表。这一行:
listOfLists[i].append(sound[windowPosition:windowPosition+ windowSize+1])
每次都附加一个列表,但我认为它是将元素附加到现有列表。
例如,如果listOfLists是:
[ [1,2,3] ]
然后,listOfLists [0] .append([4,5,6])将给出:
[ [ [1,2,3],[4,5,6] ] ]
但我在期待:
[ [1,2,3,4,5,6] ]
用下面的代码替换有问题的行对我有用:
for v in sound[windowPosition:windowPosition+windowSize+1]:
listOfLists[i].append(v)