用python写一边录音一边播音一边显示FFT波形视窗的三线程程序
时间: 2023-10-04 19:12:34 浏览: 80
vc 同时录音和播放录音的多线程程序
5星 · 资源好评率100%
以下是用Python实现一边录音一边播音一边显示FFT波形视窗的三线程程序的示例代码:
```python
import pyaudio
import numpy as np
import threading
import time
import matplotlib.pyplot as plt
# Define audio parameters
RATE = 44100
CHUNK = 1024
# Create PyAudio object
p = pyaudio.PyAudio()
# Initialize audio streams
stream_in = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK)
stream_out = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, output=True, frames_per_buffer=CHUNK)
# Initialize FFT plot
fig, ax = plt.subplots()
xf = np.linspace(0, RATE/2, CHUNK/2)
line, = ax.plot(xf, np.zeros(CHUNK/2))
ax.set_ylim(0, 0.5)
ax.set_xlim(0, RATE/2)
ax.set_xlabel('Frequency (Hz)')
ax.set_ylabel('Amplitude')
# Define thread for recording audio
def record_audio():
while True:
data_in = stream_in.read(CHUNK)
data_in = np.frombuffer(data_in, dtype=np.int16)
np.savetxt('input.txt', data_in)
stream_out.write(data_in)
# Define thread for updating FFT plot
def update_fft():
while True:
data_in = np.loadtxt('input.txt')
fft = np.fft.fft(data_in)
fft = np.abs(fft[:CHUNK//2]) / (CHUNK//2)
line.set_ydata(fft)
fig.canvas.draw()
fig.canvas.flush_events()
# Start threads
threading.Thread(target=record_audio).start()
threading.Thread(target=update_fft).start()
# Keep program running
while True:
time.sleep(1)
```
这个程序使用PyAudio库来录制和播放音频,使用NumPy库进行FFT计算,使用Matplotlib库来实时绘制FFT波形。程序创建了两个线程,一个用于录制音频并将数据保存到文件中,另一个用于从文件中读取数据并计算FFT并更新FFT波形视窗。程序还使用了一个while循环来保持程序运行,直到手动停止程序。
阅读全文