moonFFTmusic

    Real-time audio spectrum visualizer using FFT

    Download zip
    Author
    Version
    0.1.4
    License
    Apache-2.0
    Last updated
    26 days ago
    Downloads
    78

    No dependencies

    #moonFFTmusic

    CI License: Apache-2.0

    https://mooncakes.io/docs/IvanAXu/moonFFTmusic@0.1.4

    A real-time audio spectrum visualizer written in MoonBit. It reads a WAV file, performs Fast Fourier Transform (FFT) on audio chunks, and displays a live frequency spectrum as a beautiful ANSI bar chart in the terminal.

    Spectrum Analyzer Screenshot

    #Features

    #Audio Engine (CPU-Optimized)

    • WAV File Reader: Parses RIFF/WAVE headers and reads 16-bit signed PCM audio (mono and stereo). Samples are normalized to [-1.0, 1.0].
    • SoA FFT Engine: Iterative radix-2 Cooley-Tukey FFT using Structure of Arrays (separate Array[Double] for real/imaginary parts). The butterfly hot loop uses inline double arithmetic with unsafe_get/unsafe_set — zero object allocations per frame (vs ~15,000 allocations/frame in the original Complex-based approach).
    • Single Twiddle Table: Twiddle factors are precomputed once at startup as a single table of size N/2. All FFT stages reuse this table via strided indexing (twiddle(j) = tw[j * stride]), eliminating per-stage trigonometric recomputation.
    • Precomputed Hann Window: Window coefficients are computed once at startup and applied via direct array multiplication — no per-frame cos calls.
    • Pre-allocated FFT Buffers: re[] and im[] arrays are allocated once and reused across all frames — zero per-frame array allocations.

    #Visual Display (21 enhancements)

    #FeatureDescription
    1Attack/release envelopeFast rise (0.7), slow fall (0.15) — natural amplitude decay
    2Spatial smoothingIn-place 3-tap blur [0.2, 0.6, 0.2] with rolling buffer (no temp array)
    3Row-level brightness gradient3D glow effect — top of bars brighter, bottom dimmer
    4Left-side dB scaleProfessional meter labels: 0dB, -12, -24, -36, -48
    5Segmented RMS meterGreen (<60%) → yellow (<85%) → red zones with dB readout
    6Peak hold markersBold ━ with exponential decay (×0.88 per frame)
    7Separator line── between header and spectrum area
    8Musical note detectionShows note name + octave + cents (e.g., A#4+, A3-)
    9Bar groupingSubtle gap every 3 bars for cleaner visual separation
    10Bottom glow reflection3-row dim mirror of spectrum with fading intensity
    11Dashed reference line┄ pattern at -12dB, · at gap positions
    12Bar topsTop cell is a fractional block flush on the body (no half-cell gap)
    13Peak frequency markerDominant bar's contour glyph glows yellow on the envelope row
    14Vertical frequency gridFaint ╎ at label positions (50Hz – 10kHz)
    15Magnitude-based colorBrightness = 50% row position + 50% magnitude ratio
    16True-color 24-bit RGB gradientSmooth HSL-based rainbow (blue→cyan→green→yellow→red) with a white-glow core, using \u001b[38;2;R;G;Bm, precomputed per-bar
    17Beat detection with pulse glowRMS energy history tracking; border flashes warm orange on detected beats, ♫ indicator in header
    18Waveform stripTime-domain signal display at bottom showing the actual audio waveform shape

    #Performance Optimizations Summary

    OptimizationBeforeAfterImpact
    FFT data layoutArray[Complex] (3 allocs/butterfly)Array[Double] re/im (0 allocs)~15,000 fewer allocs/frame
    Twiddle factorsRecomputed per stage (log₂N times)Single table, strided lookupEliminates N/2 cos/sin calls/frame
    Hann windowRecomputed per framePrecomputed once at startupEliminates N cos calls/frame
    Bin mappinglog_freq_bin() per bar per framePrecomputed bin_map[] arrayEliminates 60 pow/log2 calls/frame
    Grid detectionLinear search per bar per rowPrecomputed is_grid[] boolean arrayO(1) lookup vs O(k) search
    Frequency labelsO(n²) string concatenationStringBuilderLinear-time label rendering
    Spatial smoothingTemp array allocation per frameIn-place rolling bufferZero per-frame array allocs
    FFT buffersAllocated per framePre-allocated, reusedZero per-frame array allocs
    Color tableArray[Array[String]] (2D, double indirection)Flat Array[String] with bar*nbl+level indexOne array access vs two per bar per row
    Height processing4 separate loops over num_bars2 fused loops (height+envelope, smoothing+peak)Halves loop overhead
    Row invariantsrow_contrib[row] + beat_boost recomputed per barHoisted as row_base per rowEliminates 1560 redundant additions/frame
    Bar offsetbar * num_brightness_levels per bar per rowPrecomputed bar_offsets[] arrayEliminates 1560 multiplications/frame
    Color table accessSafe ctx.color_table[bar][level]color_tbl.unsafe_get(bar_off + level)Bypasses bounds check in hot path
    Bin aggregationSafe ctx.bin_starts[bar] accessunsafe_get + local referenceBypasses bounds check
    Waveform fillSafe array accessunsafe_set/unsafe_getBypasses bounds check
    Total time stringformat_time(total, rate) per framePrecomputed once at startupEliminates string formatting per frame
    Frequency label textO(60×8) nested loop + format_freq per framePrecomputed label_strings[] arrayEliminates 480 iterations + string formatting/frame
    dB scale labelshsl_to_rgb per row per framePrecomputed db_scale_labels[] arrayEliminates 20 hsl_to_rgb calls/frame
    Waveform colorsString interpolation per bar per framePrecomputed 9×256=2304 color tableEliminates 60 string interpolations/frame
    Sparkline colorsString interpolation per bar per framePrecomputed 4×8=32 color tableEliminates 60 string interpolations/frame
    bar_offsets arrayArray::makei per framePrecomputed in DisplayContextEliminates 1 array allocation/frame
    bar_fade arrayArray::make per frameReusable field in PeakTrailEliminates 1 array allocation/frame
    Height double conversionto_double() × height_factor per bar per rowPrecomputed heights_d[] before row loopEliminates 2400 to_double+multiply/frame
    IIR anti-flicker stateArray[Int32] (integer IIR can't eliminate ±1 oscillation)Array[Double] (float IIR before quantization)Eliminates residual ±1 flicker
    Dominant bar markerRaw dominant_bar recomputed per frameSticky dom_bar passed from main.mbtEliminates dominant-marker jumping
    Rainbow hue rotationrotate_hue() 1920 string allocs/framePrecomputed 40 color tables, swap indexZero per-frame string allocs
    heights_d/peak_heights_dArray::make per framePre-allocated in DisplayContextEliminates 120 Double allocs/frame
    Terminal heightFixed max_height=26 (45 lines/frame)Auto-detect LINES env varEliminates scroll flicker on small terminals
    Layout compaction45 lines/frame (header+sep+26 bars+5 glow+...)30 lines/frame (removed sep, glow 5→3)Fits 30-line terminals

    #How to Run

    #Prerequisites

    Install the MoonBit CLI:

    # Unix (Linux / macOS) curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash # Verify installation moon version

    #Method 1: One-command script (easiest)

    cd moonFFTmusic # Generate a 440Hz test tone and visualize it ./run.sh # Specify a WAV file and FFT size ./run.sh assets/chord.wav 1024

    The script automatically generates a test WAV if the file doesn't exist, builds the project, and starts the visualizer.

    #Method 2: Manual commands (most control)

    cd moonFFTmusic # Step 1: Generate a test WAV file python3 scripts/gen_wav.py assets/test.wav music # 120BPM loop: kick+bass+chords+hats python3 scripts/gen_wav.py assets/chord.wav chord # Chord: 220+440+880+2000Hz # Step 2: Build the project moon build --target native # Step 3: Run the visualizer moon run src/main assets/test.wav 1024

    #Method 3: Run the compiled binary directly

    cd moonFFTmusic moon build --target native # Binary location after build ./_build/native/debug/build/src/main/main.exe assets/test.wav 1024

    #Using your own WAV files

    Any 16-bit PCM WAV file works:

    moon run src/main /path/to/your/song.wav 2048

    #Arguments

    ArgumentRequiredDefaultDescription
    wav_fileYes—Path to a 16-bit PCM WAV file
    fft_sizeNo1024FFT window size, must be power of 2

    #Compute device

    The device is auto-selected at startup: if a GPU is detectable it is loaded and reported, otherwise the visualizer falls back to CPU.

    DetectionNode probed
    NVIDIA/dev/nvidia0 … /dev/nvidia15
    AMD / Intel (DRM)/dev/dri/card0 … card7, /dev/dri/renderD128 … renderD135
    CPU fallbackno GPU node found

    CUDA_VISIBLE_DEVICES=-1 (or empty) forces CPU even when a GPU is present. The chosen device is printed on startup, e.g. Compute device: GPU (NVIDIA, /dev/nvidia0).

    Valid FFT sizes: 256, 512, 1024, 2048, 4096, 8192, ...

    #Colour schemes (cava-style)

    Pick a palette with the third argument: ./run.sh assets/test.wav 1024 <scheme>

    SchemeDescription
    rainbow (default)Hue anchored to frequency (indigo bass → red treble) with an aurora hue rotation
    fireRed base → yellow crest, painted by loudness — every column shares one flame ramp
    iceViolet base → cyan crest, painted by loudness — a cold crystalline look

    fire/ice also recolour the scheme-aware accents: the beat border glows amber / crystal instead of cyan, the header's Peak / note / BPM values shift to warm gold-coral / icy blue-violet, and the WV waveform traces a warm ember ramp instead of the cool blue one — so no data element clashes with its palette. The app also sets the terminal window title (OSC 2), like btop. The progress bar (cyan→violet) and the level meters (green→red) stay scheme-independent: they are UI semantics, not data.

    rainbow keeps colour = frequency; fire/ice trade that for a height-coded gradient (cava semantics), so the waterfall follows the same ramp.

    Larger FFT sizes give better frequency resolution but slower time response. Smaller sizes give better time resolution but coarser frequency bins.

    #What you'll see

    ╔━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╗ ║ 🎵 MoonFFTmusic — Real-time Spectrum Analyzer ║ ║ 44100Hz | FFT 1024 | Peak 43Hz (F1-) ♫ | 120 BPM | 0:1.0 ║ ╚━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╝ │ ╱────╱╱──────────────╲╲∨╱╱──╲╲╲╲──────────────╱╱──∨──╲╲───── │ 🎹 ▮▏│▏││▏│▏│▏││▏│▏││▏│▏│▏│ C3-C5 ♥ ○○●○ │0dB ╎ ████████████▆▃ ╎ ╎ ╎ ╎ ╎ │ ╎ ██████████████ ╎ ╎ ╎ ╎ ╎ │ ━━━━━━██████████████ ╎ ╎ ╎ ╎ ╎ │ ━━━━━▇██████████████ ╎ ╎ ╎ ╎ ╎ │ ━━━━━███████████████━━╎ ▁ ╎ ╎ ╎ ╎ │ ━━━━━███████████████━━╎ █━ ╎ ╎ ╎ ╎ │ ━━━━━███████████████━━╎ ██━ ╎ ╎ ╎ ╎ │-6dB ━━━━▇███████████████▄━╎ ██━ ╎ ╎ ╎ ╎ │ ┄━━━━█████████████████━╎┄┄██━┄╎┄┄┄┄┄╎┄┄┄┄┄┄┄┄╎┄┄┄┄┄┄╎┄┄┄┄┄┄┄ │ ━━━━█████████████████━╎ ██━ ╎ ╎ ╎ ╎ │ ▆▆▆▆█████████████████━╎ ██━ ╎ ╎ ╎ ╎ │ █████████████████████━╎ ██━ ╎ ╎ ╎ ╎ │ ━█████████████████████━━ ━██▆ ╎ ╎ ╎ ╎ │ ━█████████████████████━━━━███━╎ ╎ ╎ ╎ │-12dB━█████████████████████━━━▅███━╎ ╎ ╎ ╎ │ ━█████████████████████━━━████━╎ ╎ ╎ ╎ │ ━██████████████████████━━████━╎ ╎ ╎ ━━ ╎ │ ▇██████████████████████━━████━╎ ╎ ╎ ━━ ━━ │ ███████████████████████━━████━╎ ╎ ╎ ━━ ━━ │ ███████████████████████━━████▇╎ ╎ ╎ ▃▃━━━ │-18dB███████████████████████━▃█████━ ╎ ╎ ██━▄▄ │ ███████████████████████▃██████━ ╎ ╎ ██▁██ │ ██████████████████████████████━ ╎ ╎ ━█████━ │ ██████████████████████████████▂ ╎ ╎ ━█████━ │ ███████████████████████████████ ╎ ╎ ▇█████▃ │ ███████████████████████████████━ ╎ ╎ ███████ │ ███████████████████████████████▁ ╎ ╎━███████━ │-24dB████████████████████████████████ ╎ ╎████████▄ │ ████████████████████████████████▁ ╎ ━█████████━ │ █████████████████████████████████ ╎ ██████████▆ │ █████████████████████████████████▆ ╎ ▅███████████▄ │ ██████████████████████████████████▇▂╎ ▁▆█████████████▅▁ │ ████████████████████████████████████▆▄▃▃▄▆█████████████████▆ └───────────────────────────────────────────────────────────────── 50Hz 100Hz 200Hz 500Hz 1kHz 2kHz 5kHz 10kHz WV ⠴⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠲⠖⠒⠒⠒⠒⠒⠒⠒⠦⠤⠤⠤⢤⣀⡤⣄⣀⣀⣀⣀⣀⣀⣠⠤⠖⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠶⠒⠒⠒ BASS ██████████░░░░ MID ████████░░░░░░ TREB ███░░░░░░░░░░░ RMS: [████████████████████████████████░░░░░░░░░░░░] -16.9 dB ║║║║║║║║║║║║║║║║║║║║║▓░░░░░░░░░░░░░░░░░░░░ 50% 0:1.0 / 0:2.0

    Bars use smooth 24-bit true-color RGB gradient with rainbow hue rotation — the entire color spectrum flows and shifts over time like an aurora. The header border flashes white-yellow on strong beats (═ → ━). Below the main bars, a 3-row spectrogram waterfall shows recent spectrum history: each column keeps the same hue as its live bar, and the newest row is the brightest so the three rows read as a time sequence. The WV line is a Braille-dot oscilloscope (like cli-visualizer's wave mode): 120 samples trace a continuous curve through 2×4 dot cells, auto-gained per window so quiet passages keep their shape. BASS / MID / TREB meters and the RMS bar all use the same absolute -60..0 dB scale as the spectrum. Rendering runs at ~42 fps (16 ms tick) while the FFT/data update stays on a 48 ms cadence (every 2nd render frame) — all per-frame animations (rainbow rotation, scanline, peak-cap gravity) get double smoothness at 1x playback, with every decay constant rescaled to the new tick. Terminal height is auto-detected via LINES env var — the frame always fits exactly, without scroll flicker. Terminals shorter than 24 lines automatically drop the piano keyboard and band-meter rows (cava-style: shrink the chrome, keep the spectrum). Press Ctrl+C to stop.

    #Visual Effects (14 dynamic effects)

    EffectDescription
    🌈 Rainbow hue rotationColor spectrum flows and shifts 3°/frame like aurora (rainbow scheme)
    🏔️ Monstercat smoothingNeighbor fill from cava: tall bars prop up valleys (h[j] ← h[i]/1.5^|i-j|), reading as continuous ridges instead of sawtooth
    📌 Peak capscava-style: bright-white ━ cap holds above each bar, then falls with accelerating gravity
    ⚡ Beat flash borderAccents flash white-hot, soft beats warm; ═→━ on strong hits
    💥 Beat bloomFast beat pulse + sustained intensity brighten all bars
    👑 Bar top crownTopmost fractional cell gets +8 brightness — glowing crest
    📡 ScanlineA +2 brightness row sweeps up/down across spectrum
    🔦 Dominant spotlightMain frequency bar + neighbors brighten on beat pulses
    📊 Progress pulseCyan→violet progress bar (distinct from spectrum) pulses on beats
    🎚️ RMS beat glowRMS label turns yellow on strong beats
    🌊 Spectrogram waterfall3-row scrolling history; per-frequency hue (matches bars) with intensity brightness
    🎹 Piano keyboard2-octave mini keyboard with detected note highlighted ▮
    🎵 BPM estimationBeat timing analysis with ♥/♡ indicator and BPM display in header
    🥁 Rhythm indicator4-step beat marker advancing with each detected beat
    🔊 Frequency band metersBASS/MID/TREBLE 10-cell horizontal energy meters
    🎛️ Auto-gain controlDynamic sensitivity adjustment for quiet/loud sections
    🎶 Note detectionReal-time MIDI note name (e.g. G4+) with cents deviation

    #MoonBit Language Features

    This project leverages MoonBit-specific features for performance and safety:

    FeatureUsage
    #derive(Debug)Auto-generated debug output for Complex, WavData, GpuInfo, ComputeDevice
    Array::unsafe_get/unsafe_setBypass bounds check in FFT butterfly hot loop (SoA)
    Array::mapi_in_placeIn-place Hann window application (Complex path)
    Array::makeiFunctional array construction for precomputed tables
    StringBuilderEfficient string building for all terminal output
    Double::clamp / Int32::clampSafe value clamping with labeled arguments
    match patternsChunk type dispatch, arg parsing, bar render states, HSL→RGB
    guard patternsEarly return on file not found / parse failure
    test blocks32 inline tests for FFT correctness, SoA FFT, WAV parsing, args
    enum + matchChunkType/BarState enums for dispatch
    mut struct fieldsMutable BeatDetector state (history_idx, beat_intensity)
    Bit tricksn & (n-1) for power-of-2 check, bit-reversal permutation
    SoA patternSeparate Array[Double] re/im for zero-alloc FFT
    Precomputed tablesTwiddle factors, Hann window, bin mapping, bar colors — all computed once at startup

    #Testing

    # Run all 32 inline tests moon test --target native # Type check with no warnings moon check --target native --deny-warn # Format check moon fmt --check

    #CI

    GitHub Actions CI runs on every push to main/dev* and on every pull request.

    1. Build & Test (Ubuntu + macOS) — moon check and moon fmt --check run as advisory checks (toolchain version drift must not fail CI); moon build and moon test (32 inline tests) are blocking
    2. Integration (Ubuntu) — Generate WAV files, run visualizer, verify output, test multiple FFT sizes, verify error handling

    #Project Structure

    moonFFTmusic/ ├── .github/workflows/ci.yml # GitHub Actions CI ├── src/main/ │ ├── moon.pkg # Package imports │ ├── fft.mbt # FFT engine (Complex + SoA) + tests │ ├── wav.mbt # WAV parser + tests │ ├── device.mbt # GPU/CPU device detection + selection │ ├── display.mbt # ANSI renderer (18 effects, true-color, beat detection) │ └── main.mbt # Entry point + SoA FFT loop + arg parsing + tests ├── scripts/ │ └── gen_wav.py # WAV file generator (sine/chord/music modes) ├── assets/ │ ├── chord.wav # Demo chord WAV (220+440+880+2000Hz) │ └── test.wav # Demo music loop (120BPM, dynamic) ├── run.sh # Build & run script ├── moon.mod # Module definition └── README.md

    #License

    Apache License 2.0