嗨,所以我的Windows机器上的程序运行良好,但是我在树莓派上遇到了错误,我不确定为什么,因为据我所知,在分配之前没有引用数据。我不确定该如何解决此问题,将不胜感激。 这是代码
import pyaudio
import numpy
import math
import matplotlib.pyplot as plt
import matplotlib.animation
from multiprocessing import Process
import time
RATE = 44100
BUFFER = 882
p = pyaudio.PyAudio()
stream = p.open(
format = pyaudio.paFloat32,
channels = 1,
rate = RATE,
input = True,
output = False,
frames_per_buffer = BUFFER
)
fig = plt.figure()
line1 = plt.plot([],[])[0]
line2 = plt.plot([],[])[0]
r = range(0,int(RATE/2+1),int(RATE/BUFFER))
l = len(r)
def init_line():
line1.set_data(r, [-1000]*l)
line2.set_data(r, [-1000]*l)
return (line1,line2,)
# def grab():
# time.sleep(3)
# print(line1.get_data())
# # return (line1,line2,)
def update_line(i):
try:
data = numpy.fft.rfft(numpy.fromstring(
stream.read(BUFFER), dtype=numpy.float32)
)
except IOError:
pass
data = numpy.log10(numpy.sqrt(
numpy.real(data)**2+numpy.imag(data)**2) / BUFFER) * 10
line1.set_data(r, data)
line2.set_data(numpy.maximum(line1.get_data(), line2.get_data()))
# print(data[0])
if data[0] > -30:
print("red")
elif data[0] <-30 and data[0]>-50:
print("amber")
else: print("green")
# if linee2[0].any() >2000:
# print("red")
# else: print("green")
return (line1,line2,)
plt.xlim(0, RATE/2+1)
plt.ylim(-60, 0)
plt.xlabel('Frequency')
plt.ylabel('dB')
plt.title('Spectrometer')
plt.grid()
line_ani = matplotlib.animation.FuncAnimation(
fig, update_line, init_func=init_line, interval=0, blit=True
)
plt.show()
这是运行时输出的错误
numpy.real(data)**2+numpy.imag(data)**2) / BUFFER) * 10
UnboundLocalError: local variable 'data' referenced before assignment```