从FFT求突出频率

2024-05-13 12:08:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为音频频谱分析器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


Tags: fromimportselffftgithubtruedatastream
2条回答

我发现一些代码使用问题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.")

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

相关问题 更多 >