用python生成一边录音一边显示MFCC画布的多线程程序
时间: 2024-05-03 13:21:54 浏览: 204
vc 同时录音和播放录音的多线程程序
5星 · 资源好评率100%
以下是用Python编写的一边录音一边显示MFCC画布的多线程程序:
```python
import pyaudio
import numpy as np
import matplotlib.pyplot as plt
import librosa
import threading
# 设置录音参数
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
# 创建PyAudio对象
p = pyaudio.PyAudio()
# 创建MFCC画布
fig, ax = plt.subplots()
im = ax.imshow(np.zeros((13, 50)), cmap='hot', interpolation='nearest', origin='lower')
fig.canvas.draw()
# 定义线程类
class RecordThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.frames = []
def run(self):
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
while True:
data = stream.read(CHUNK)
self.frames.append(data)
def get_frames(self):
return self.frames
# 定义线程类
class MFCCThread(threading.Thread):
def __init__(self, record_thread):
threading.Thread.__init__(self)
self.record_thread = record_thread
def run(self):
while True:
frames = self.record_thread.get_frames()
y = np.frombuffer(b''.join(frames), dtype=np.int16)
mfcc = librosa.feature.mfcc(y=y, sr=RATE)
im.set_data(mfcc)
fig.canvas.draw()
# 创建录音线程和MFCC线程
record_thread = RecordThread()
mfcc_thread = MFCCThread(record_thread)
# 启动线程
record_thread.start()
mfcc_thread.start()
# 显示MFCC画布
plt.show()
# 停止录音和PyAudio对象
record_thread.join()
p.terminate()
```
该程序使用PyAudio库进行录音,并使用LibROSA库生成MFCC特征。程序创建两个线程,一个用于录音并获取音频数据,另一个用于生成MFCC特征并在Matplotlib图形上显示。程序使用Matplotlib库创建MFCC图形,并在循环中更新图形数据。最后,程序启动两个线程并显示MFCC图形。
阅读全文