i was making a sound visualiser in pygame . here is my source code:
#importing packages
import pygame,math
import sounddevice as sd
#colors
COLOR = {
'Black':[0,0,0],
'White':[255,255,255],
'Red':{255,0,0},
'Yellow':[255,255,0],
'Green':[0,255,0],
'Blue':[0,0,255]
}
#function to get value equal to or between min and max value
def clamp(min_value, max_value, value):
if value < min_value:
return min_value
if value > max_value:
return max_value
return value
# class to draw bars in drawing
class AudioBar:
def __init__(self, cx, cy, color,angle, width=1, min_height=20, max_height=300, extend=False):
self.cx, self.cy= cx, cy
self.color = color
self.prev_height = min_height
self.width, self.min_height, self.max_height = width, min_height, max_height
self.angle = math.radians(angle)
self.ax,self.ay=cx,cy
# update position of bar
def update(self,height):
height = height * 1000
height = clamp(self.min_height,self.max_height,height)
if height<self.prev_height:
height = self.prev_height -(height*0.1)
else:
height = self.prev_height + (height*0.1)
self.ax = self.cx+(math.sin(self.angle)*height)
self.ay = self.cy+(math.cos(self.angle)*height)
self.prev_height = height
return self
# for rendering on screen
def render(self, screen)->None:
pygame.draw.line(screen,
self.color,
[self.cx,self.cy],
[self.ax,self.ay] ,
self.width)
# function to get data from input stream
#i am not get live data . help!
def getData() -> list:
data,_ = stream.read(360)
data = data.flatten()
return data
# main function
def main()-> None:
pygame.init()
screen = pygame.display.set_mode([500,500])
bars =[]
#range is 360 to draw lines on 360 angles
for angle in range(360):
bars.append(
AudioBar(
250,250,
COLOR['Black'],
angle))
while True:
data= getData()
screen.fill(COLOR['White'])
for i,d in enumerate(data):
bars[i].update(d).render(screen)
pygame.display.flip()
try:
stream = sd.InputStream(
device=1, channels=1)
with stream:
main()
except Exception as e:
raise e
it worked out pretty well but there is unwanted plus sign + kind of pattern in drawing.
can this be fixed?
and one more thing out of question ,in stream the data which i am getting is not new but old which is getting render afterwards. I want live data.And also it to look good.