Add configurable graph smoothing

Smooth the spectrum graph by averaging the last N values.
This commit is contained in:
Correl Roush 2020-09-26 20:46:40 -04:00
parent 271364b046
commit cbd7993275
2 changed files with 9 additions and 3 deletions

View file

@ -41,6 +41,7 @@
[50, [255, 255, 0]], [50, [255, 255, 0]],
[75, [255, 0, 0]] [75, [255, 0, 0]]
], ],
"lines": [100, 100, 100] "lines": [100, 100, 100],
"smoothing": 5
} }
} }

View file

@ -1,10 +1,11 @@
from bisect import bisect from bisect import bisect
from collections import deque
import logging import logging
from multiprocessing import Queue from multiprocessing import Queue
import os import os
import queue import queue
from statistics import fmean from statistics import fmean
from typing import Iterable, List, Optional, Tuple, Union from typing import Deque, Iterable, List, Optional, Tuple, Union
import numpy as np # type: ignore import numpy as np # type: ignore
import pygame # type: ignore import pygame # type: ignore
@ -29,6 +30,7 @@ class Plot:
(0, (255, 255, 255)), (0, (255, 255, 255)),
], ],
lines_color: Tuple[int, int, int] = (128, 128, 128), lines_color: Tuple[int, int, int] = (128, 128, 128),
smoothing: int = 5,
) -> None: ) -> None:
self.screen = screen self.screen = screen
self.x = x self.x = x
@ -39,6 +41,7 @@ class Plot:
self.bar_colors = bar_colors self.bar_colors = bar_colors
self.lines_color = lines_color self.lines_color = lines_color
self.audio = models.PCM(44100, 2) self.audio = models.PCM(44100, 2)
self.spectrums: Deque[np.array] = deque(maxlen=smoothing)
def spectrum(self) -> np.array: def spectrum(self) -> np.array:
data = np.fromstring(self.audio.raw, dtype=np.int16) data = np.fromstring(self.audio.raw, dtype=np.int16)
@ -49,7 +52,8 @@ class Plot:
fft = fft[: len(fft) // 2] fft = fft[: len(fft) // 2]
dbfs = 20 * np.log10(fft * 2 / (len(fft) * 2 ** 15)) dbfs = 20 * np.log10(fft * 2 / (len(fft) * 2 ** 15))
dbfs = np.maximum(-100, dbfs) + 100 dbfs = np.maximum(-100, dbfs) + 100
return dbfs self.spectrums.append(dbfs)
return np.mean(np.column_stack(self.spectrums), axis=1)
def draw_lines(self) -> None: def draw_lines(self) -> None:
data = self.spectrum() data = self.spectrum()
@ -162,6 +166,7 @@ def main():
], ],
), ),
lines_color=config.get("lines", (128, 128, 128)), lines_color=config.get("lines", (128, 128, 128)),
smoothing=config.get("smoothing", 5),
) )
try: try: