我有一个输入的音频流,通过我的麦克风来读取,我对这些数据进行FFT计算,我想要的是在Y轴上绘制FFT的幅值数据,在X轴上进行FFT频率数据的更新(例如,20 FFT),基本上看起来像这样( 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()发布于 2019-05-17 14:26:33
我不能为您生成数据,但是我编写了一个示例,它更新循环中的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。
发布于 2020-04-20 23:18:34
请尝试以下代码:
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()https://stackoverflow.com/questions/56178261
复制相似问题