我有一个通过我的麦克风传入的音频流,pyaudio正在读取该音频,我正在对该数据执行FFT计算,我想在Y轴上绘制FFT振幅数据,在X轴上绘制FFT频率数据并以(例如说20fps)更新,基本上看起来像这样(https://www.youtube.com/watch?v=Tu8p2pywJAs&t=93s),但左侧的频率较低,而右侧的频率较高。我所拥有的代码就是我所拥有的
我是python的新手,更不用说以任何形式编写代码了,因此不胜感激,但是请尽量将其保持在易于理解的术语内,如果我要详细说明,请尊重我,非常感谢任何人谁给我他们的时间!
import pyaudio
import numpy as np
import time
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from matplotlib import style
pa = pyaudio.PyAudio()
callback_output = []
def callback(in_data, frame_count, time_info, flag):
audio_data = np.fromstring(in_data, dtype=np.int16)
callback_output.append(audio_data)
return None,pyaudio.paContinue
stream = pa.open(format=pyaudio.paInt16,
channels=1,
rate=44100,
output=False,
input=True,
stream_callback=callback)
stream.start_stream()
fig = plt.gcf()
fig.show()
fig.canvas.draw()
while stream.is_active():
fft_data = np.fft.fft(callback_output)
fft_freq = np.fft.fftfreq(len(fft_data))
plt.plot(fft_freq,fft_data)
plt.xlim(min(fft_freq),max(fft_freq))
fig.canvas.draw()
plt.pause(0.05)
fig.canvas.flush_events()
fig.clear()
stream.close()
pa.terminate()
答案 0 :(得分:0)
我无法为您生成数据,但是我写了一个示例,该示例可以循环更新matplotlib图:
import matplotlib.pyplot as plt
import numpy as np
import time
plt.ion() # Stop matplotlib windows from blocking
# Setup figure, axis and initiate plot
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = ax.plot([], [], 'ro-')
while True:
time.sleep(0.5)
# Get the new data
xdata = np.arange(10)
ydata = np.random.random(10)
# Reset the data in the plot
ln.set_xdata(xdata)
ln.set_ydata(ydata)
# Rescale the axis so that the data can be seen in the plot
# if you know the bounds of your data you could just set this once
# so that the axis don't keep changing
ax.relim()
ax.autoscale_view()
# Update the window
fig.canvas.draw()
fig.canvas.flush_events()
您应该只需要更改循环中分配xdata和ydata的行,即可使其适用于您的数据。
如果要在左侧获得低频,则可能要在fftfreq和fftdata上使用np.fft.fftshift:https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftshift.html
答案 1 :(得分:0)
请尝试以下代码:
while stream.is_active():
fft_data = np.fft.rfft(callback_output) # rfft removes the mirrored part that fft generates
fft_freq = np.fft.rfftfreq(len(callback_output), d=1/44100) # rfftfreq needs the signal data, not the fft data
plt.plot(fft_freq, np.absolute(fft_data)) # fft_data is a complex number, so the magnitude is computed here
plt.xlim(np.amin(fft_freq), np.amax(fft_freq))
fig.canvas.draw()
plt.pause(0.05)
fig.canvas.flush_events()
fig.clear()