|
| 1 | +from adafruit_led_animation.animation import Animation |
| 2 | + |
| 3 | +class Volume(Animation): |
| 4 | + """ |
| 5 | + Animate the brightness and number of pixels based on volume. |
| 6 | + :param pixel_object: The initialised LED object. |
| 7 | + :param float speed: Animation update speed in seconds, e.g. ``0.1``. |
| 8 | + :param brightest_color: Color at max volume ``(r, g, b)`` tuple, or ``0x000000`` hex format |
| 9 | + """ |
| 10 | + |
| 11 | + def __init__(self, pixel_object, speed, brightest_color, decoder, max_volume=500, name=None): |
| 12 | + self._decoder = decoder |
| 13 | + self._num_pixels = len(pixel_object) |
| 14 | + self._max_volume = max_volume |
| 15 | + self._brigthest_color = brightest_color |
| 16 | + super().__init__(pixel_object, speed, brightest_color, name=name) |
| 17 | + |
| 18 | + def _set_color(self, brightest_color): |
| 19 | + self.colors = [brightest_color] |
| 20 | + |
| 21 | + def map_range(self, x, in_min, in_max, out_min, out_max): |
| 22 | + mapped = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min |
| 23 | + if out_min <= out_max: |
| 24 | + return max(min(mapped, out_max), out_min) |
| 25 | + |
| 26 | + return min(max(mapped, out_max), out_min) |
| 27 | + |
| 28 | + def draw(self): |
| 29 | + red = int(self.map_range(self._decoder.rms_level, 0, self._max_volume, 0, self._brigthest_color[0])) |
| 30 | + green = int(self.map_range(self._decoder.rms_level, 0, self._max_volume, 0, self._brigthest_color[1])) |
| 31 | + blue = int(self.map_range(self._decoder.rms_level, 0, self._max_volume, 0, self._brigthest_color[2])) |
| 32 | + |
| 33 | + lit_pixels = int(self.map_range(self._decoder.rms_level, 0, self._max_volume, 0, self._num_pixels)) |
| 34 | + if lit_pixels > self._num_pixels: |
| 35 | + lit_pixels = self._num_pixels |
| 36 | + |
| 37 | + self.pixel_object[0:lit_pixels] = [(red,green,blue)] * lit_pixels |
| 38 | + self.pixel_object[lit_pixels:self._num_pixels] = [(0,0,0)] * (self._num_pixels-lit_pixels) |
0 commit comments