从FFT查找显着频率

问题描述 投票:-1回答:2

我已经使用音频频谱分析仪https://github.com/markjay4k/Audio-Spectrum-Analyzer-in-Python/blob/master/audio%20spectrum_pt2_spectrum_analyzer.ipynb的代码段设置了python音频流和fft(我删除了所有绘图代码,我想从我的fft中找到最突出的频率。

import numpy as np
import pyaudio
import struct
from scipy.fftpack import fft
import sys
import time


class AudioStream(object):
    def __init__(self):

        # stream constants
        self.CHUNK = 1024 * 2
        self.FORMAT = pyaudio.paInt16
        self.CHANNELS = 1
        self.RATE = 44100
        self.pause = False

        # stream object
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(
            format=self.FORMAT,
            channels=self.CHANNELS,
            rate=self.RATE,
            input=True,
            output=True,
            frames_per_buffer=self.CHUNK,
        )
        self.start_recording()

    def start_recording(self):

        print('stream started')

        while True:
            #Get data from stream and unpack to data_int
            data = self.stream.read(self.CHUNK)
            data_int = struct.unpack(str(2 * self.CHUNK) + 'B', data)

            # compute FFT
            yf = fft(data_int)

            # find the most prominent frequency from this fft


if __name__ == '__main__':
    AudioStream()

以下是github上非自适应音频频谱分析仪的输出的屏幕截图,显示了我想从fft(最显着的频率)获得的值。在这种情况下,该值约为1555Hz。

Image of desired value

python scipy fft frequency-analysis audio-analysis
2个回答
0
投票

如果yf是fft的结果,那么您需要在其中找到最大值,对吗?如果它是一个numpy数组,则amax()函数将在这里为您提供帮助。 @DarrylG会为您指明正确的方向; Print highest peak value of the frequency domain plot


0
投票

我发现了一些使用问题Audio Frequencies in Python执行此操作的代码,下面将其保留:

            # compute FFT
            fftData=abs(np.fft.rfft(data_int))**2
            # find the maximum
            which = fftData[1:].argmax() + 1
            # use quadratic interpolation around the max
            if which != len(fftData)-1:
                y0,y1,y2 = np.log(fftData[which-1:which+2:])
                x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
                # find the frequency and output it
                thefreq = (which+x1)*self.RATE/self.CHUNK
                print(f"The freq is {thefreq} Hz.")
            else:
                thefreq = which*self.RATE/self.CHUNK
                print (f"The freq is {thefreq} Hz.")
© www.soinside.com 2019 - 2024. All rights reserved.