用python制作一边录音一边播音一边显示FFT波形pyqt5一个开始按键的三线程程序
时间: 2023-10-05 14:05:40 浏览: 113
以下是一个用Python和PyQt5制作的一边录音一边播音一边显示FFT波形的三线程程序,包含一个开始按键:
```python
import sys
import pyqtgraph as pg
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
from PyQt5.QtCore import Qt, QThread
import numpy as np
import sounddevice as sd
class AudioRecorderThread(QThread):
def __init__(self, callback_function, parent=None):
super(AudioRecorderThread, self).__init__(parent)
self.callback_function = callback_function
def run(self):
duration = 1
sample_rate = 44100
channels = 1
samples = int(duration * sample_rate)
audio_data = sd.rec(samples, samplerate=sample_rate, channels=channels)
sd.wait()
self.callback_function(audio_data)
class AudioPlayerThread(QThread):
def __init__(self, audio_data, parent=None):
super(AudioPlayerThread, self).__init__(parent)
self.audio_data = audio_data
def run(self):
sd.play(self.audio_data, blocking=True)
class FFTThread(QThread):
def __init__(self, audio_data, parent=None):
super(FFTThread, self).__init__(parent)
self.audio_data = audio_data
def run(self):
fft_data = np.abs(np.fft.rfft(self.audio_data))
fft_data = np.log10(fft_data)
self.emit(Qt.QueuedConnection, fft_data)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle('Audio Recorder Player FFT')
self.resize(800, 600)
self.start_button = QPushButton('Start', self)
self.start_button.setGeometry(10, 10, 80, 30)
self.start_button.clicked.connect(self.start_recording)
self.graph_widget = pg.PlotWidget(self)
self.graph_widget.setGeometry(10, 50, 780, 540)
self.graph_widget.setRange(xRange=[0, 22050], yRange=[-10, 10])
self.recorder_thread = None
self.player_thread = None
self.fft_thread = None
def start_recording(self):
self.start_button.setEnabled(False)
self.graph_widget.clear()
self.graph_widget.plotItem.setTitle('FFT')
self.recorder_thread = AudioRecorderThread(self.audio_data_callback)
self.recorder_thread.start()
def audio_data_callback(self, audio_data):
self.player_thread = AudioPlayerThread(audio_data)
self.player_thread.start()
self.fft_thread = FFTThread(audio_data)
self.fft_thread.finished.connect(self.fft_data_callback)
self.fft_thread.start()
def fft_data_callback(self, fft_data):
self.graph_widget.plot(fft_data, pen='r')
self.start_button.setEnabled(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
```
该程序使用了三个线程:`AudioRecorderThread`用于录音,`AudioPlayerThread`用于播放录音,`FFTThread`用于计算FFT波形。主窗口包含一个开始按键和一个用于显示FFT波形的绘图部件。开始按键按下后,程序会先启动`AudioRecorderThread`线程进行录音,然后启动`AudioPlayerThread`线程播放录音,最后启动`FFTThread`线程计算FFT波形并在绘图部件中显示。程序中使用了`sounddevice`库进行录音和播放音频,使用了`pyqtgraph`库进行绘图。
阅读全文