用python写一边录音一边播放一边显示FFT波形的多线程程序
时间: 2023-10-04 21:12:38 浏览: 64
以下是使用Python编写的一边录音一边播放一边显示FFT波形的多线程程序:
```python
import pyaudio
import numpy as np
import threading
import time
import matplotlib.pyplot as plt
# 定义一些常量
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
# 创建 PyAudio 对象
p = pyaudio.PyAudio()
# 创建用于录音和播放的流
stream_in = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK_SIZE)
stream_out = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
output=True,
frames_per_buffer=CHUNK_SIZE)
# 创建用于显示FFT波形的线程
class FFTThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.daemon = True
self.fig, self.ax = plt.subplots()
self.ax.set_ylim(0, 100)
self.ax.set_xlim(0, 20000)
self.line, = self.ax.plot([], [])
def run(self):
while True:
data = np.fromstring(stream_in.read(CHUNK_SIZE), dtype=np.int16)
fft_data = np.abs(np.fft.fft(data))[:int(CHUNK_SIZE/2)]
freqs = np.fft.fftfreq(CHUNK_SIZE, 1.0/RATE)[:int(CHUNK_SIZE/2)]
self.line.set_data(freqs, fft_data)
self.fig.canvas.draw()
self.fig.canvas.flush_events()
# 开始录音和播放
stream_out.start_stream()
# 创建并启动线程
fft_thread = FFTThread()
fft_thread.start()
while True:
data = stream_in.read(CHUNK_SIZE)
stream_out.write(data)
# 停止录音和播放
stream_in.stop_stream()
stream_out.stop_stream()
# 关闭 PyAudio 对象
p.terminate()
```
这个程序中,我们创建了一个 `FFTThread` 类,用于显示FFT波形。在 `run()` 方法中,我们读取音频数据,计算FFT并绘制波形。然后,我们创建了一个 `FFTThread` 对象并启动它的线程。最后,在主线程中,我们不断读取音频数据并播放它们。