用python生成一边录音一边显示FFT画布canvas的多线程程序
时间: 2024-06-01 16:03:38 浏览: 162
FFT.zip_fft_fft python_python FFT程序_python fft
以下是一个使用Python生成一边录音一边显示FFT画布canvas的多线程程序的示例代码:
```python
import pyaudio
import numpy as np
import tkinter as tk
import threading
class AudioProcessor:
def __init__(self, chunk_size=1024, sample_rate=44100):
self.chunk_size = chunk_size
self.sample_rate = sample_rate
self.audio_buffer = np.zeros(chunk_size)
self.fft_buffer = np.zeros(chunk_size)
self.p = pyaudio.PyAudio()
self.stream = self.p.open(format=pyaudio.paInt16, channels=1, rate=self.sample_rate, input=True, frames_per_buffer=self.chunk_size)
def process(self):
while True:
data = self.stream.read(self.chunk_size)
self.audio_buffer = np.frombuffer(data, dtype=np.int16)
self.fft_buffer = np.abs(np.fft.fft(self.audio_buffer))
def close(self):
self.stream.stop_stream()
self.stream.close()
self.p.terminate()
class CanvasProcessor:
def __init__(self, canvas, width=800, height=400):
self.canvas = canvas
self.width = width
self.height = height
self.canvas.config(width=self.width, height=self.height, bg="black")
self.line = self.canvas.create_line(0, self.height/2, self.width, self.height/2, fill="white", width=2)
def process(self):
while True:
fft = audio_processor.fft_buffer
fft = fft[:self.width//2]
fft = np.log10(fft + 1)
fft = fft / np.max(fft)
fft = fft * self.height/2
fft = fft.astype(int)
for i, y in enumerate(fft):
x = i*2
self.canvas.coords(self.line, x, self.height/2-y, x+2, self.height/2-y)
def close(self):
pass
def start():
global audio_processor, canvas_processor
audio_processor = AudioProcessor()
canvas_processor = CanvasProcessor(canvas)
t1 = threading.Thread(target=audio_processor.process)
t2 = threading.Thread(target=canvas_processor.process)
t1.start()
t2.start()
def stop():
global audio_processor, canvas_processor
audio_processor.close()
canvas_processor.close()
root = tk.Tk()
root.title("Audio FFT")
canvas = tk.Canvas(root)
canvas.pack()
start_button = tk.Button(root, text="Start", command=start)
start_button.pack(side="left")
stop_button = tk.Button(root, text="Stop", command=stop)
stop_button.pack(side="right")
root.mainloop()
```
该程序创建了两个类:`AudioProcessor`和`CanvasProcessor`。`AudioProcessor`类使用PyAudio库进行音频录制,每次录制一个指定大小的音频块,然后计算其FFT,并将结果存储在缓冲区中。`CanvasProcessor`类使用Tkinter库创建画布,并在每次循环中根据FFT缓冲区的内容更新画布。
程序使用两个线程:一个用于处理音频,另一个用于更新画布。程序还提供了“Start”和“Stop”按钮,以便启动和停止音频录制和画布更新。
阅读全文