我正在绘制来自audiojack的实时音频数据,并试图将整个信号放在一个图中(从第0秒到当前);因此,我将音频信号附加到一个列表中(即“在我的情况下合并”)并一次又一次地绘制更新的列表,但随着数据的增加(即合并中的元素数量),绘图变得越来越慢。任何提高速度的建议,请记住,我需要从头到尾包含所有数据点,以包括情节。
请在下面找到我的代码
import pyaudio
import itertools
import numpy as np
import time
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter
import matplotlib.animation as animation
RATE = 44100
CHUNK = int(RATE/2) # RATE / number of updates per second
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_ylim([-1,1])
line, = ax.plot([], [],'-k',label='red')
ax.legend()
frames = []
# define callback (2)
def callback(in_data, frame_count, time_info, status):
# convert data to array
data = (np.fromstring(in_data, dtype=np.float32))
frames.append(data)
return (in_data, pyaudio.paContinue)
if __name__=="__main__":
# instantiate PyAudio (1)
p = pyaudio.PyAudio()
# open stream using callback (3)
stream = p.open(format=pyaudio.paFloat32,
channels=1,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
stream_callback=callback)
# start the stream (4)
stream.start_stream()
tt = 0
xar = []
while stream.is_active():
if frames:
t1 = time.time()
def animate(i):
#data is appended in the frames (global variable is pulled out every time one cycle of plotting is over
data_out= frames.pop()
xar.append(data_out.tolist())
merged = list(itertools.chain.from_iterable(xar)) #merging of audio data
line.set_ydata(merged)
line.set_xdata(range(len(merged)))
ax.relim()
ax.autoscale_view()
data_filter = []
data_out = []
print((time.time() - t1) % 60)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
# close stream and connection
stream.close()
p.terminate()
# wait for stream to finish (5)