2012-01-31 129 views
11

我試圖用Python來檢索現場音頻輸入的主頻。目前我正在嘗試使用筆記本電腦內置麥克風的音頻流,但在測試下面的代碼時,我得到的結果非常糟糕。Python中的頻率分析

# Read from Mic Input and find the freq's 
    import pyaudio 
    import numpy as np 
    import bge 
    import wave 

    chunk = 2048 

    # use a Blackman window 
    window = np.blackman(chunk) 
    # open stream 
    FORMAT = pyaudio.paInt16 
    CHANNELS = 1 
    RATE = 1920 

    p = pyaudio.PyAudio() 
    myStream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk) 

    def AnalyseStream(cont): 
     data = myStream.read(chunk) 
     # unpack the data and times by the hamming window 
     indata = np.array(wave.struct.unpack("%dh"%(chunk), data))*window 
     # Take the fft and square each value 
     fftData=abs(np.fft.rfft(indata))**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)*RATE/chunk 
      print("The freq is %f Hz." % (thefreq)) 
     else: 
      thefreq = which*RATE/chunk 
      print("The freq is %f Hz." % (thefreq)) 

    # stream.close() 
    # p.terminate() 

的代碼是從this question,與波形文件的傅立葉分析涉及蠶食。它是在當前的模塊化結構中,因爲我正在使用Blender Game Environment(因此在頂部導入bge)來實現它,但是我非常確定我的問題在於AnalyseStream模塊。

任何意見,你可以提供將不勝感激。

更新:我得到正確的值,每隔一次又一次,但他們很少發現不正確的值(< 10Hz)。那個和程序真的很慢。

+1

1920的採樣率看起來很腥。更典型的音頻採樣率是8000或44100.你用什麼樣的聲音來進行正確性測試?如果它不是來自正弦波發生器,那麼您聽到的音高和頻率峯值可能會非常不同。 – hotpaw2 2012-01-31 16:31:51

回答

6

你好,發現實時分析的FFT的最大計算速度有點慢。

如果您不能使用複雜的波形來查找頻率,那麼您可以使用基於時域的任何方法,例如性能會更好的過零點。

在去年我做了一個簡單的函數來計算過零點的頻率。

#Eng Eder de Souza 01/12/2011 
#ederwander 
from matplotlib.mlab import find 
import pyaudio 
import numpy as np 
import math 


chunk = 1024 
FORMAT = pyaudio.paInt16 
CHANNELS = 1 
RATE = 44100 
RECORD_SECONDS = 20 


def Pitch(signal): 
    signal = np.fromstring(signal, 'Int16'); 
    crossing = [math.copysign(1.0, s) for s in signal] 
    index = find(np.diff(crossing)); 
    f0=round(len(index) *RATE /(2*np.prod(len(signal)))) 
    return f0; 


p = pyaudio.PyAudio() 

stream = p.open(format = FORMAT, 
channels = CHANNELS, 
rate = RATE, 
input = True, 
output = True, 
frames_per_buffer = chunk) 

for i in range(0, RATE/chunk * RECORD_SECONDS): 
    data = stream.read(chunk) 
    Frequency=Pitch(data) 
    print "%f Frequency" %Frequency 

ederwander