Crafting Terminal TUIs with Real-Time Audio Visualization in Python
Under the hood of ttune: orchestrating FFmpeg audio streams, Fourier transform frequency binning, and curses RGB color pairs in Linux terminals.
Bringing Multimedia into the Linux Console
Terminal applications possess an enduring elegance: they start instantaneously, use negligible RAM, and integrate seamlessly into tmux or tiling window managers. In developing ttune, the vision was to create a terminal music player capable of playing any media container (from MP3 and FLAC to MP4 and MKV) while rendering a full-color, animated frequency spectrum in pure text cells.
Stream Decoding via Subprocess FFmpeg
Rather than compiling cumbersome C bindings for dozens of codecs, ttune delegates raw stream decoding to FFmpeg through an asynchronous pipe. Raw 16-bit PCM audio samples are streamed into Python, where fast Fourier transforms (FFT) compute discrete frequency magnitudes.
import subprocess, numpy as np
def spawn_audio_pipeline(file_path):
cmd = [
'ffmpeg', '-i', file_path,
'-f', 's16le', '-ac', '2', '-ar', '44100',
'-loglevel', 'quiet', '-'
]
return subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=4096)
def calculate_spectrum_bars(raw_chunk, num_bars=32):
# Convert raw bytes to integer numpy array
samples = np.frombuffer(raw_chunk, dtype=np.int16)
if len(samples) == 0:
return [0] * num_bars
fft_data = np.abs(np.fft.rfft(samples))
# Logarithmic grouping of frequency bins into visual bars
bins = np.array_split(fft_data, num_bars)
return [min(100, int(np.mean(b) / 50)) for b in bins]RGB Curses Rendering
Terminal colors in curses are managed via color pair definitions. ttune configures 256-color gradient tables that transition from electric blue to violet as audio amplitude rises, creating an authentic retro equalizer aesthetic directly in terminal cells.