class GraphicsCircleTest(object): def __init__(self): self.graphics = Graphics(matrix_width, matrix_height) self.radius = 0 self.direction = 1 self.color = RED def generate(self): # clear the drawing surface self.graphics.fill(BLACK) # put a circle on our surface self.graphics.drawCircle(matrix_width / 2, matrix_height / 2, self.radius, self.color) # circle grows and shrinks based on direction. if self.direction: self.radius += 1 else: self.radius -= 1 # if the circle is to big or to small inverse growth direction. if self.radius >= (matrix_height / 2) or self.radius <= 0: self.direction = not self.direction # get the surface drawn return self.graphics.getSurface()
class VisualizerCircle(object): def __init__(self): self.graphics = Graphics(matrix_width, matrix_height) self.graphics.fill(BLUE) self.color = BLUE self.timer = Timer(0) self.chunk = 1024 self.scale = 55 self.exponent = 2 self.samplerate = 44100 self.audio_params = (pyaudio.paInt16, 1, self.samplerate, True, self.chunk) self.p = pyaudio.PyAudio() self.stream = self.p.open(format=self.audio_params[0], channels=self.audio_params[1], rate=self.audio_params[2], input=self.audio_params[3], frames_per_buffer=self.audio_params[4]) self.data = self.stream.read(self.chunk) def calculate_levels(self, data, chunk, samplerate, points=6, maxi=0): # Use FFT to calculate volume for each frequency MAX=maxi # Convert raw sound data to Numpy array fmt = "%dH"%(len(data)/2) data2 = struct.unpack(fmt, data) data2 = numpy.array(data2, dtype='h') # Apply FFT fourier = numpy.fft.fft(data2) ffty = numpy.abs(fourier[0:len(fourier)/2])/1000 ffty1=ffty[:len(ffty)/2] ffty2=ffty[len(ffty)/2::]+2 ffty2=ffty2[::-1] ffty=ffty1+ffty2 ffty=numpy.log(ffty)-2 fourier = list(ffty)[4:-4] fourier = fourier[:len(fourier)/2] size = len(fourier) # Add up for 6 lights levels = [sum(fourier[i:(i+size/points)]) for i in xrange(0, size, size/points)][:points] return levels def getaudio(self): try: raw = self.stream.read(self.audio_params[5]) except IOError as e: if e[1] != pyaudio.paInputOverflowed: raise else: print("Warning: audio input buffer overflow") raw = '\x00' * self.audio_params[5] return np.array(np.frombuffer(raw, np.int16), dtype=np.float64) def generate(self): self.graphics.fill(BLACK) if self.stream.get_read_available(): self.data = self.stream.read(self.chunk) levels = self.calculate_levels(self.data, self.chunk, self.samplerate, matrix_height) for i, level in enumerate(levels): self.color = color_convert(interp_color(level/max(levels))) level = max(min(level/self.scale, 1.0), 0.0) level = level**self.exponent level = int(level*0xff) self.graphics.drawCircle(matrix_width/2, matrix_height/2, level, self.color) return self.graphics.getSurface() def __del__(self): print("Closing Stream") self.stream.close() self.p.terminate()