如何得到每个频段的平均fft值?

How to get the average fft value of each frequency band?

大家好,我正在尝试获取 7 个频段的平均 fft 值 这是到目前为止的代码。它与日志功能一起使用。 问题是我想要每个波段的 平均 fft 值 我怎样才能做到这一点? 有人告诉我要获得较低的索引,但我无法弄清楚 现在对我来说越来越复杂了。 这是代码>>

import pyaudio
import numpy as np
import math
np.set_printoptions(suppress=True) # don't use scientific notation

CHUNK = 2048 # number of data points to read at a time
RATE = 44100 # time resolution of the recording device (Hz)


p=pyaudio.PyAudio() # start the PyAudio class
stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True,
              frames_per_buffer=CHUNK) #uses default input device

#maxValue            = 2**16
# 7 Freq Bands

NUM_BAND = 7
lower = 0
d = math.log10(CHUNK/2-1)/NUM_BAND


for i in range(1): #to it a few times just to see
    try:
        data = np.fromstring(stream.read(CHUNK),dtype=np.int16)
        fft = abs(np.fft.fft(data).real)
        fft = fft[:int(len(fft)/2)] # keep only first half

        freq = np.fft.fftfreq(CHUNK,1.0/RATE)
        freq = freq[:int(len(freq)/2)] # keep only first half


        band_lower = []
        for i in range(NUM_BAND):
            higher = round(math.pow(10,(i+1)*d))
            print("Band %d from freq[%d]=%f to freq[%d]=%f"%(i, lower, 
            freq[lower], higher, freq[higher]))
            lower = higher+1

    except KeyboardInterrupt:
        stream.stop_stream()
        stream.close()
        p.terminate()

这是打印输出

Band 0 from freq[0]=0.000000 to freq[3]=64.599609
Band 1 from freq[4]=86.132812 to freq[7]=150.732422
Band 2 from freq[8]=172.265625 to freq[19]=409.130859
Band 3 from freq[20]=430.664062 to freq[52]=1119.726562
Band 4 from freq[53]=1141.259766 to freq[141]=3036.181641
Band 5 from freq[142]=3057.714844 to freq[380]=8182.617188
Band 6 from freq[381]=8204.150391 to freq[1023]=22028.466797

您可以使用 np.average 计算平均值:

startend 是你的乐队。

import numpy as np 

a = np.array([[1, 2, 3], [4, 5, 6], [3,4,5]])

print(np.average(a[start:end], axis=0))