# Music Visualization Audio tutorial 8 of the [[Audio]] series. Previous: [[Eurorack and Unity]], which builds `AudioInputTap` (live synth audio into Unity) and `SynthMidiInput` (MIDI events). This note turns **any** audio signal, a clip, the procedural synth from [[2. OnAudioFilterRead Procedural Synth]], or your Mother-32 and Subharmonicon through an interface, into numbers and pictures. **Target:** Unity **6000.5+** (URP assumed; Shader Graph and VFX Graph steps below). The VR section targets **Unity 6.3 LTS (6000.3.27f2+)** for Quest 2 per [[0.Choosing a Unity Version]]. > [!note] Verification status > Checked 2026-11-09 against the 6000.5 Scripting Reference: > - `AudioSource.GetSpectrumData(float[] samples, int channel, FFTWindow window)`: array length must be a power of 2, **min 64, max 8192**; bins are evenly spaced from 0 to half the sample rate; it uses `AudioSettings.outputSampleRate`; the allocating overload is **obsolete**; the data is a *short history window* and the page says it "isn't suited for critical or chronological, real-time data analysis or ... scenarios where you require low latency"; buffers are created on the first call per object so data is initially empty. > - `AudioSource.GetOutputData(float[] samples, int channel)` (non-allocating; length power of 2; same history-window caveat; the allocating overload is deprecated). `FFTWindow` values: Rectangular, Triangle, Hamming, Hanning, Blackman, BlackmanHarris. > - `AudioClip.GetData`, `Microphone.GetPosition`, `Microphone.Start` as in [[Eurorack and Unity]]. > - `VisualEffect.SetFloat` (int and string overloads) and `VisualEffect.SetGraphicsBuffer` (the reference is not serialized; GraphicsBuffer is not an `Object`); `LineRenderer.SetPositions` (set `positionCount` first; indices beyond it are ignored); `Texture2D.SetPixelData` (texture must be readable, data size must equal width x height and match the format, call `Apply` after). > - VFX Graph **Sample Graphics Buffer** operator (17.5 manual: expects a Structured-target `GraphicsBuffer`; the stride must match; the Buffer input accepts only an *exposed property*; element types include float, int, uint, Vector2/3/4, Matrix4x4): https://docs.unity3d.com/Packages/[email protected]/manual/Operator-SampleBuffer.html > > **Not verified:** the VFX Graph package version that ships with each 6000.x editor (sources I found disagree; use whatever Package Manager shows), VFX Graph behaviour on Quest 2 (check [[5.VFX Graph Comparison and Performance]] and Unity's mobile/XR VFX notes before building on it), Shader Graph's exact UI wording for making a texture property global, and whether `GetOutputData` is taken before or after mixer volume on your platform. The FFT, scope, Lissajous, onset and binder scripts are mine and standard DSP; **none of the code has been compiled or play-tested in Unity.** Tune every constant by eye and ear. ## Parts of this note 1. [What are we measuring?](#1-what-are-we-measuring) 2. [One frame source for every visualizer](#2-one-frame-source-for-every-visualizer) 3. [FFT and spectrum bands](#3-fft-and-spectrum-bands) 4. [Using Unity's own GetSpectrumData (and why you might not)](#4-using-unitys-own-getspectrumdata-and-why-you-might-not) 5. [Oscilloscope](#5-oscilloscope) 6. [XY Lissajous scope](#6-xy-lissajous-scope) 7. [Envelope following and beat detection](#7-envelope-following-and-beat-detection) 8. [Driving shaders, lights and VFX Graph](#8-driving-shaders-lights-and-vfx-graph) 9. [VR and Quest: visualizing live synth input in a headset](#9-vr-and-quest-visualizing-live-synth-input-in-a-headset) 10. [Scene recipe, pitfalls, Level Up! and patterns](#10-scene-recipe-pitfalls-level-up-and-patterns) ## 1. What are we measuring? | View | Domain | Shows | Good for | Moog tip | |---|---|---|---|---| | **Oscilloscope** | Time | Waveform shape over ~5-20 ms | Wave shapes, pulse width, filter ringing | Mother-32 saw -> square -> filter sweep | | **Spectrum (FFT)** | Frequency | Energy per band | Bass/mid/high meters, "EQ bars", brightness | Subharmonicon sub-oscillators show as harmonically related peaks | | **XY scope / Lissajous** | Time, two channels | Phase and ratio between L and R | Frequency ratios, stereo phase | Subharmonicon dividers give *integer* ratios, so beautiful closed curves | | **Envelope / level** | Time, smoothed | Loudness contour | Drive scale, light, camera | Each gate opens an envelope | | **Onset / beat** | Time, event | "A hit just happened" | Cuts, particles bursts | If Unity *sent* the note you already know the onset, see 7.3 | **Resolution trade-off.** An FFT of size N at sample rate S has a bin width of S/N Hz and a window length of N/S seconds. At 48 kHz, N = 1024 gives about 47 Hz bins and ~21 ms windows: fine for bass/mid/high, too coarse to separate bass notes a semitone apart. N = 4096 gives ~12 Hz bins and ~85 ms windows: better pitch detail, smeared transients. Pick per effect. **Audio vs frame rate.** At 60 fps you get one picture per ~16.7 ms; the audio engine runs in blocks. You are sampling a stream, not tracking it sample-by-sample, which is why Unity's docs warn `GetSpectrumData`/`GetOutputData` are for analysis, not for low-latency work. ## 2. One frame source for every visualizer Rather than every script grabbing audio its own way, one component fills two buffers (left and right) once per frame, from either an `AudioSource` (clips, generators, procedural synths) or `AudioInputTap` (live interface input). Everything else reads those arrays. ### 2.1 `AudioFrameSource.cs` ```csharp using UnityEngine; /// <summary> /// Produces the latest mono-per-channel frames (Left, Right) once per frame. /// Runs early so all visualizers see this frame's data. /// </summary> [DefaultExecutionOrder(-50)] public sealed class AudioFrameSource : MonoBehaviour { public enum Mode { AudioSourceOutput, LiveInput } [SerializeField] Mode mode = Mode.LiveInput; [SerializeField] AudioSource audioSource; // for AudioSourceOutput [SerializeField] AudioInputTap inputTap; // for LiveInput (from Eurorack and Unity) [Tooltip("Power of 2 (GetOutputData requires it). 2048 = ~43 ms at 48 kHz.")] [SerializeField] int frameSize = 2048; public float[] Left { get; private set; } public float[] Right { get; private set; } public int FrameSize => frameSize; public int SampleRate { get; private set; } = 48000; public bool HasData { get; private set; } public int FrameId { get; private set; } // increments each successful fill (Dirty Flag) public float Rms { get; private set; } public float Peak { get; private set; } void Awake() { if (!Mathf.IsPowerOfTwo(frameSize)) frameSize = Mathf.NextPowerOfTwo(frameSize); Left = new float[frameSize]; Right = new float[frameSize]; } void Update() { bool ok = false; if (mode == Mode.AudioSourceOutput && audioSource != null && audioSource.isPlaying) { SampleRate = AudioSettings.outputSampleRate; audioSource.GetOutputData(Left, 0); audioSource.GetOutputData(Right, 1); // second channel; identical or silent if the source is mono ok = true; } else if (mode == Mode.LiveInput && inputTap != null && inputTap.IsRecording) { SampleRate = inputTap.SampleRate; ok = inputTap.ReadLatest(Left, 0); if (ok) { // Mono interface input: fall back to the same channel for Right. int rightCh = inputTap.Channels > 1 ? 1 : 0; ok = inputTap.ReadLatest(Right, rightCh); } } HasData = ok; if (!ok) { Rms = 0f; Peak = 0f; return; } FrameId++; double sumSq = 0.0; float peak = 0f; for (int i = 0; i < frameSize; i++) { float s = Left[i]; sumSq += s * s; float a = s < 0 ? -s : s; if (a > peak) peak = a; } Rms = (float)System.Math.Sqrt(sumSq / frameSize); Peak = peak; } } ``` `FrameId` is a **Dirty Flag**: consumers recompute only when it changes, which keeps work off the CPU when audio has stalled (Game Programming Patterns, see [[Game Programming Patterns (Review)]]). **Add the optional channel overload** to `AudioInputTap` if you wrote it before this note: `ReadLatest(float[] dest, int channel = -1)` as shown in [[Eurorack and Unity]] section 5.2 (this note assumes that signature). ## 3. FFT and spectrum bands Unity gives you `GetSpectrumData` for `AudioSource`s only. Live input from `Microphone` is an `AudioClip`, not an `AudioSource`, so we need our own transform. A radix-2 FFT is ~40 lines. ### 3.1 `RealFft.cs` ```csharp using System; /// <summary> /// In-place iterative radix-2 FFT for real input. Applies a Hann window and returns /// amplitude-normalised magnitudes (a full-scale sine centred on a bin is ~1.0). /// Allocation-free after construction. /// </summary> public sealed class RealFft { readonly int _n; readonly float[] _cos, _sin, _window, _re, _im; readonly int[] _rev; readonly float _norm; public int Size => _n; public int BinCount => _n / 2; public RealFft(int size) { if (size < 8 || (size & (size - 1)) != 0) throw new ArgumentException("FFT size must be a power of 2 >= 8"); _n = size; _cos = new float[size / 2]; _sin = new float[size / 2]; for (int k = 0; k < size / 2; k++) { double a = 2.0 * Math.PI * k / size; _cos[k] = (float)Math.Cos(a); _sin[k] = (float)Math.Sin(a); } _window = new float[size]; double sum = 0.0; for (int i = 0; i < size; i++) { _window[i] = (float)(0.5 - 0.5 * Math.Cos(2.0 * Math.PI * i / (size - 1))); sum += _window[i]; } _norm = (float)(2.0 / sum); _rev = new int[size]; int bits = 0; while ((1 << bits) < size) bits++; for (int i = 0; i < size; i++) { int r = 0; for (int b = 0; b < bits; b++) if ((i & (1 << b)) != 0) r |= 1 << (bits - 1 - b); _rev[i] = r; } _re = new float[size]; _im = new float[size]; } /// <summary>input.Length must be >= Size; magnitudes.Length must be >= BinCount.</summary> public void Magnitudes(float[] input, float[] magnitudes) { for (int i = 0; i < _n; i++) { int j = _rev[i]; _re[j] = input[i] * _window[i]; _im[j] = 0f; } for (int len = 2; len <= _n; len <<= 1) { int half = len >> 1; int step = _n / len; for (int i = 0; i < _n; i += len) { for (int j = 0; j < half; j++) { int k = j * step; float c = _cos[k], s = _sin[k]; // twiddle = c - i*s int a = i + j, b = a + half; float tr = c * _re[b] + s * _im[b]; float ti = c * _im[b] - s * _re[b]; _re[b] = _re[a] - tr; _im[b] = _im[a] - ti; _re[a] += tr; _im[a] += ti; } } } int bins = _n / 2; for (int i = 0; i < bins; i++) magnitudes[i] = Mathf_Sqrt(_re[i] * _re[i] + _im[i] * _im[i]) * _norm; } static float Mathf_Sqrt(float v) => (float)Math.Sqrt(v); } ``` **How it works.** `_rev` puts the input in bit-reversed order, then each pass combines pairs of half-size transforms using the twiddle factor `e^(-2*pi*i*k/N)`. We stored `cos` and `sin` of `2*pi*k/N`, so the twiddle is `c - i*s`. The Hann window tapers the frame edges so a steady tone does not "leak" into neighbouring bins; the `_norm` factor (`2 / sum(window)`) makes a full-scale sine measure about 1.0 so thresholds are meaningful. ### 3.2 `SpectrumAnalyzer.cs`: log-spaced bands, attack/release smoothing Human pitch is logarithmic, so equal-width FFT bins over-represent treble. We pool bins into **log-spaced bands** and convert magnitude to decibels. ```csharp using UnityEngine; public sealed class SpectrumAnalyzer : MonoBehaviour { [SerializeField] AudioFrameSource source; [SerializeField, Min(8)] int fftSize = 1024; // power of 2; must be <= source.FrameSize [SerializeField, Range(8, 128)] int bandCount = 32; [SerializeField] float minHz = 40f; [SerializeField] float maxHz = 16000f; [SerializeField] float dbFloor = -70f; // maps to 0 [Header("Smoothing (seconds)")] [SerializeField] float attack = 0.02f; [SerializeField] float release = 0.18f; RealFft _fft; float[] _frame, _mag; int[] _bandLo, _bandHi; float _binHz; int _builtRate; int _lastFrameId = -1; /// <summary>Smoothed band levels 0..1 (low to high frequency).</summary> public float[] Bands { get; private set; } /// <summary>Un-smoothed band levels 0..1 (used for onset detection).</summary> public float[] BandsRaw { get; private set; } public int BandCount => bandCount; public float Bass { get; private set; } // ~20-250 Hz public float Mid { get; private set; } // ~250-4000 Hz public float High { get; private set; } // ~4000 Hz+ /// <summary>True on frames where a new analysis was produced.</summary> public bool Updated { get; private set; } void Awake() { Bands = new float[bandCount]; BandsRaw = new float[bandCount]; _bandLo = new int[bandCount]; _bandHi = new int[bandCount]; } void Rebuild() { fftSize = Mathf.Min(Mathf.NextPowerOfTwo(fftSize), source.FrameSize); _fft = new RealFft(fftSize); _frame = new float[fftSize]; _mag = new float[fftSize / 2]; _builtRate = source.SampleRate; _binHz = (float)_builtRate / fftSize; float nyquist = _builtRate * 0.5f; float top = Mathf.Min(maxHz, nyquist); for (int b = 0; b < bandCount; b++) { float f0 = minHz * Mathf.Pow(top / minHz, (float)b / bandCount); float f1 = minHz * Mathf.Pow(top / minHz, (float)(b + 1) / bandCount); int lo = Mathf.Clamp(Mathf.FloorToInt(f0 / _binHz), 1, fftSize / 2 - 1); int hi = Mathf.Clamp(Mathf.CeilToInt(f1 / _binHz), lo, fftSize / 2 - 1); _bandLo[b] = lo; _bandHi[b] = hi; } } void Update() { Updated = false; if (source == null || !source.HasData || source.FrameId == _lastFrameId) return; _lastFrameId = source.FrameId; if (_fft == null || _builtRate != source.SampleRate) Rebuild(); // Most recent fftSize samples of the Left channel: the tail of the frame. System.Array.Copy(source.Left, source.FrameSize - fftSize, _frame, 0, fftSize); _fft.Magnitudes(_frame, _mag); float dt = Time.unscaledDeltaTime; float aCoef = 1f - Mathf.Exp(-dt / Mathf.Max(0.0001f, attack)); float rCoef = 1f - Mathf.Exp(-dt / Mathf.Max(0.0001f, release)); for (int b = 0; b < bandCount; b++) { float m = 0f; for (int i = _bandLo[b]; i <= _bandHi[b]; i++) if (_mag[i] > m) m = _mag[i]; // max-pool float db = 20f * Mathf.Log10(m + 1e-7f); float v = Mathf.Clamp01((db - dbFloor) / -dbFloor); BandsRaw[b] = v; float cur = Bands[b]; Bands[b] = cur + (v - cur) * (v > cur ? aCoef : rCoef); } Bass = AverageHz(20f, 250f); Mid = AverageHz(250f, 4000f); High = AverageHz(4000f, maxHz); Updated = true; } float AverageHz(float f0, float f1) { int lo = Mathf.Clamp(Mathf.FloorToInt(f0 / _binHz), 1, fftSize / 2 - 1); int hi = Mathf.Clamp(Mathf.CeilToInt(f1 / _binHz), lo, fftSize / 2 - 1); float sum = 0f; for (int i = lo; i <= hi; i++) sum += _mag[i]; float avg = sum / (hi - lo + 1); float db = 20f * Mathf.Log10(avg + 1e-7f); return Mathf.Clamp01((db - dbFloor) / -dbFloor); } } ``` **Why these choices** - **Max-pooling** a band's bins (rather than averaging) keeps a single strong synth partial visible; averaging over many bins hides it. - **dB mapping.** Linear magnitudes squash everything quiet to nothing. `dbFloor = -70` maps -70 dBFS to 0 and 0 dBFS to 1. Raise the floor (e.g. -50) for more contrast. - **Attack/release** is a one-pole smoother per band, time-based (`1 - exp(-dt/tau)`) so it behaves the same at 30 or 144 fps. Fast attack and slow release looks like a classic analyser. - If the source sample rate changes (the live device rate differs from Project Settings), `Rebuild()` reallocates and recomputes the band edges. ### 3.3 A first display: bars ```csharp using UnityEngine; /// <summary>Instantiates N cubes and scales them with the band levels. Simple, GPU-instancing friendly.</summary> public sealed class SpectrumBars : MonoBehaviour { [SerializeField] SpectrumAnalyzer analyzer; [SerializeField] Transform barPrefab; [SerializeField] float spacing = 0.12f; [SerializeField] float maxHeight = 3f; Transform[] _bars; void Start() { int n = analyzer.BandCount; _bars = new Transform[n]; for (int i = 0; i < n; i++) { var t = Instantiate(barPrefab, transform); t.localPosition = new Vector3((i - n * 0.5f) * spacing, 0f, 0f); _bars[i] = t; } } void Update() { var b = analyzer.Bands; for (int i = 0; i < _bars.Length; i++) { float h = Mathf.Max(0.02f, b[i] * maxHeight); _bars[i].localScale = new Vector3(spacing * 0.8f, h, spacing * 0.8f); _bars[i].localPosition = new Vector3((i - _bars.Length * 0.5f) * spacing, h * 0.5f, 0f); } } } ``` ## 4. Using Unity's own GetSpectrumData (and why you might not) For anything playing through an `AudioSource` (a clip, or the `OnAudioFilterRead` synth from tutorial 6), Unity can do the FFT for you: ```csharp using UnityEngine; [RequireComponent(typeof(AudioSource))] public sealed class UnitySpectrumProbe : MonoBehaviour { [SerializeField] int samples = 1024; // power of 2, 64..8192 [SerializeField] FFTWindow window = FFTWindow.BlackmanHarris; float[] _spectrum; AudioSource _src; public float[] Spectrum => _spectrum; public float BinHz => AudioSettings.outputSampleRate * 0.5f / samples; void Awake() { _src = GetComponent<AudioSource>(); _spectrum = new float[samples]; } void Update() { if (!_src.isPlaying) return; _src.GetSpectrumData(_spectrum, 0, window); // non-allocating overload } } ``` Use it when: the audio is already in an `AudioSource`, you want less code, and you are happy with Unity's window choice and speed. Notes from the docs and from the numbers: - **`numSamples` = array length = number of frequency bins.** Bins span **0 to half the sample rate**, so bin width is `sampleRate / 2 / samples`: with 1024 samples at 48 kHz, ~23 Hz per bin. (Our own `RealFft` uses `fftSize / 2` bins over the same span, so *its* bin width is `sampleRate / fftSize`: same thing, different parameter meaning. Do not mix them up when converting Hz to bin index.) - Allocate the array once (the allocating overload is obsolete). - Values are linear and not normalised like `RealFft`; you will need to retune `dbFloor`. - The page says it is for analysis, not low-latency work, and that data is empty until enough audio has been processed. - **It cannot see the Microphone clip** unless you play it through an `AudioSource`, and playing it means latency and a feedback risk ([[Eurorack and Unity]] section 5.3). That is why this tutorial's live path analyses the clip directly. ## 5. Oscilloscope A scope shows the waveform *shape* over a few milliseconds. The trick that makes it look like a scope rather than random wiggles is a **trigger**: start drawing each frame at the same point in the cycle (a rising zero crossing), so a steady tone appears to stand still. ### 5.1 `ScopeDisplay.cs` ```csharp using UnityEngine; [RequireComponent(typeof(LineRenderer))] public sealed class ScopeDisplay : MonoBehaviour { [SerializeField] AudioFrameSource source; [SerializeField, Range(64, 1024)] int points = 512; [SerializeField] float width = 4f; [SerializeField] float height = 1f; [SerializeField] float gain = 1f; [Tooltip("Trigger level (-1..1). A rising crossing of this level starts the trace.")] [SerializeField, Range(-0.5f, 0.5f)] float triggerLevel = 0f; [Tooltip("Samples of the frame to skip at the start, so there is room for the trigger search.")] [SerializeField] int searchSamples = 1024; LineRenderer _line; Vector3[] _pos; int _lastFrame = -1; void Awake() { _line = GetComponent<LineRenderer>(); _line.useWorldSpace = false; _line.positionCount = points; // must be set before SetPositions _pos = new Vector3[points]; } void Update() { if (source == null || !source.HasData || source.FrameId == _lastFrame) return; _lastFrame = source.FrameId; float[] x = source.Left; int max = source.FrameSize - points; int search = Mathf.Min(searchSamples, max); int start = 0; for (int i = 1; i < search; i++) { if (x[i - 1] < triggerLevel && x[i] >= triggerLevel) { start = i; break; } } for (int i = 0; i < points; i++) { float px = ((float)i / (points - 1) - 0.5f) * width; float py = Mathf.Clamp(x[start + i] * gain, -1f, 1f) * height * 0.5f; _pos[i] = new Vector3(px, py, 0f); } _line.SetPositions(_pos); } } ``` **Setting it up.** Add a `LineRenderer` to an empty GameObject, assign an unlit material (URP *Particles/Unlit* or a Shader Graph unlit), set width ~0.02, then add `ScopeDisplay`. At 48 kHz, 512 points is ~10.7 ms of audio, so a 100 Hz tone shows about one cycle and a 440 Hz tone about five. **What you will see from the rack.** A Mother-32 saw is a ramp; a square is flat-topped; sweeping the filter closes the harmonics until the shape rounds toward a sine. If the live input is AC-coupled you will see the waveform centred on zero even if the real signal has a DC offset ([[Eurorack and Unity]] section 6). ## 6. XY Lissajous scope An XY scope plots **left against right**: `x = Left[i]`, `y = Right[i]`. Equal sines in phase give a diagonal line; 90 degrees out of phase gives a circle; a 2:1 frequency ratio gives a figure-eight; other integer ratios give closed knots. The Subharmonicon's sub-oscillators are integer subdivisions of the VCOs, which is exactly the kind of ratio this display makes visible. To get two different oscillators onto L and R, patch VCO 1 to the interface's input 1 and VCO 2 to input 2 (through safe levels, [[Eurorack and Unity]] section 6.1). That requires your interface to expose *two* channels to Unity; if the `Microphone` API gives you a mono clip (not verified), use a stereo source or a software oscillator pair instead. ### 6.1 `LissajousDisplay.cs` ```csharp using UnityEngine; [RequireComponent(typeof(LineRenderer))] public sealed class LissajousDisplay : MonoBehaviour { [SerializeField] AudioFrameSource source; [SerializeField, Range(128, 2048)] int points = 1024; [SerializeField] float radius = 1f; [SerializeField] float gain = 1f; [Tooltip("Goniometer view: rotate 45 degrees so mono is a vertical line (mid/side).")] [SerializeField] bool goniometer = false; LineRenderer _line; Vector3[] _pos; int _lastFrame = -1; void Awake() { _line = GetComponent<LineRenderer>(); _line.useWorldSpace = false; _line.positionCount = points; _pos = new Vector3[points]; } void Update() { if (source == null || !source.HasData || source.FrameId == _lastFrame) return; _lastFrame = source.FrameId; int offset = source.FrameSize - points; // newest samples const float invSqrt2 = 0.70710678f; for (int i = 0; i < points; i++) { float l = source.Left[offset + i] * gain; float r = source.Right[offset + i] * gain; float x = goniometer ? (l - r) * invSqrt2 : l; float y = goniometer ? (l + r) * invSqrt2 : r; _pos[i] = new Vector3(x * radius, y * radius, 0f); } _line.SetPositions(_pos); } } ``` **Make it look like a phosphor scope.** Real XY scopes leave a fading glow. The cheap version: give the line a `TrailRenderer`-like feel by rendering the `LineRenderer` camera into a RenderTexture that is faded each frame by a translucent black quad (a feedback loop), or use a Shader Graph material with a gradient along the line. Both are rendering tutorials in their own right; see [[URP Shaders and Shader Graph]]. **A practical stability tip.** Two free-running oscillators drift in phase, so the curve rotates through its family: that is the Lissajous show. If you want a *still* figure, patch the same clock/sync to both. A purely software test: feed `AudioSourceOutput` mode with two sines (one per channel) from [[2. OnAudioFilterRead Procedural Synth]] and watch 1:1, 1:2, 2:3 ratios. ## 7. Envelope following and beat detection ### 7.1 `EnvelopeFollower.cs` An envelope follower turns the waveform into a smooth loudness contour (rectify, then smooth with fast attack and slower release), and adds a gate with hysteresis so you can get "note on/off" events from audio. ```csharp using System; using UnityEngine; public sealed class EnvelopeFollower : MonoBehaviour { [SerializeField] AudioFrameSource source; [SerializeField] float attack = 0.005f; [SerializeField] float release = 0.12f; [SerializeField, Range(0f, 1f)] float gateOn = 0.15f; [SerializeField, Range(0f, 1f)] float gateOff = 0.08f; [SerializeField] float gain = 3f; public float Value { get; private set; } // 0..1 public bool GateOpen { get; private set; } public event Action GateOpened; public event Action GateClosed; int _lastFrame = -1; void Update() { if (source == null || !source.HasData) { Value = Mathf.MoveTowards(Value, 0f, Time.unscaledDeltaTime * 4f); return; } if (source.FrameId == _lastFrame) return; _lastFrame = source.FrameId; float target = Mathf.Clamp01(source.Rms * gain); float dt = Time.unscaledDeltaTime; float tau = target > Value ? attack : release; Value += (target - Value) * (1f - Mathf.Exp(-dt / Mathf.Max(0.0001f, tau))); if (!GateOpen && Value >= gateOn) { GateOpen = true; GateOpened?.Invoke(); } else if (GateOpen && Value <= gateOff) { GateOpen = false; GateClosed?.Invoke(); } } } ``` **Why RMS and not peak.** `AudioFrameSource.Rms` is the root-mean-square of the 2048-sample frame, which tracks perceived loudness better than a single peak sample. A frame is ~43 ms, so the *attack time you can see* is bounded by that, not by the `attack` field. For tighter transients, shrink the frame (1024 or 512) or read only the tail. **The two thresholds** (`gateOn` > `gateOff`) form a **hysteresis** band so noise near one threshold does not chatter the gate on and off. A Mother-32 note held with a slow release closes the gate only when the tail drops under `gateOff`. ### 7.2 `OnsetDetector.cs`: spectral flux with an adaptive threshold An onset (a drum hit, a plucky note) is a sudden *increase* in energy in some bands. **Spectral flux** sums the positive change in each band since the previous analysis; a hit shows as a spike. A fixed threshold fails when the track gets louder, so compare to a rolling mean plus a multiple of the standard deviation. ```csharp using System; using UnityEngine; public sealed class OnsetDetector : MonoBehaviour { [SerializeField] SpectrumAnalyzer analyzer; [SerializeField, Range(10, 120)] int historyLength = 43; // analyses, ~0.7 s at 60 fps [SerializeField] float sensitivity = 1.6f; // std-devs above the mean [SerializeField] float minFlux = 0.35f; // ignore tiny wiggles [SerializeField] float refractorySeconds = 0.12f; [Header("Bands considered (0..bandCount-1)")] [SerializeField] int firstBand = 0; [SerializeField] int lastBand = 15; // bass + low mids with 32 bands public event Action<float> Onset; // strength (flux above the threshold) public float LastFlux { get; private set; } public float Threshold { get; private set; } /// <summary>Decays from 1 to 0 after each onset: handy for driving flashes.</summary> public float Pulse { get; private set; } [SerializeField] float pulseDecayPerSecond = 5f; float[] _prev, _hist; int _head, _filled; float _lastOnsetTime = -10f; void Start() { _prev = new float[analyzer.BandCount]; _hist = new float[historyLength]; lastBand = Mathf.Min(lastBand, analyzer.BandCount - 1); } void Update() { Pulse = Mathf.Max(0f, Pulse - pulseDecayPerSecond * Time.unscaledDeltaTime); if (!analyzer.Updated) return; var raw = analyzer.BandsRaw; float flux = 0f; for (int b = firstBand; b <= lastBand; b++) { float d = raw[b] - _prev[b]; if (d > 0f) flux += d; _prev[b] = raw[b]; } LastFlux = flux; // rolling mean and standard deviation over the history float mean = 0f; for (int i = 0; i < _filled; i++) mean += _hist[i]; mean = _filled > 0 ? mean / _filled : 0f; float var = 0f; for (int i = 0; i < _filled; i++) { float d = _hist[i] - mean; var += d * d; } float std = _filled > 1 ? Mathf.Sqrt(var / _filled) : 0f; Threshold = Mathf.Max(minFlux, mean + sensitivity * std); bool ready = _filled >= historyLength / 2 && Time.unscaledTime - _lastOnsetTime > refractorySeconds; if (ready && flux > Threshold) { _lastOnsetTime = Time.unscaledTime; Pulse = 1f; Onset?.Invoke(flux - Threshold); } _hist[_head] = flux; _head = (_head + 1) % historyLength; if (_filled < historyLength) _filled++; } } ``` **Tuning.** Open the Inspector in Play mode and watch `LastFlux` against `Threshold`. If it fires on every note, raise `sensitivity` or `minFlux`; if it misses soft hits, lower them. Restrict bands (`firstBand`..`lastBand`) to bass for a kick-only trigger. The refractory period stops one hit from firing twice across overlapping analysis windows. ### 7.3 When you already know the beat: use MIDI If Unity *sends* the notes, the onset time is known exactly and needs no detection. If a performer plays a keyboard into the interface, [[Eurorack and Unity]]'s `SynthMidiInput.NoteOn` event is also an exact onset. The audio you *hear* arrives later than the MIDI by the instrument's response time plus the audio return latency, so treat MIDI as the trigger and audio analysis as the *texture*. For a hardware sequencer that runs on its own (the Subharmonicon with its internal clock), audio onset detection is the only option, or send MIDI clock from Unity and count the 24-PPQN pulses yourself. ## 8. Driving shaders, lights and VFX Graph ### 8.1 `AudioReactiveBinder.cs`: publish a few clean numbers Rather than let each effect read the analyser, publish a small set of values (`Bass`, `Mid`, `High`, `Level`, `Pulse`) as **global shader floats**, VFX Graph exposed floats, and a few direct targets. ```csharp using UnityEngine; using UnityEngine.VFX; public sealed class AudioReactiveBinder : MonoBehaviour { [SerializeField] SpectrumAnalyzer analyzer; [SerializeField] OnsetDetector onset; [SerializeField] EnvelopeFollower envelope; [SerializeField] AudioFrameSource source; [Header("Optional targets")] [SerializeField] VisualEffect[] vfx; [SerializeField] Light pulseLight; [SerializeField] float lightBase = 0.5f, lightPulse = 3f; [SerializeField] Transform scaleTarget; [SerializeField] float scaleBase = 1f, scaleBass = 0.5f; // Global shader properties (declare them non-exposed in Shader Graph to use them as globals). static readonly int GBass = Shader.PropertyToID("_AudioBass"); static readonly int GMid = Shader.PropertyToID("_AudioMid"); static readonly int GHigh = Shader.PropertyToID("_AudioHigh"); static readonly int GLevel = Shader.PropertyToID("_AudioLevel"); static readonly int GPulse = Shader.PropertyToID("_AudioPulse"); // VFX Graph exposed property names (create these in the graph's Blackboard). static readonly int VBass = Shader.PropertyToID("Bass"); static readonly int VMid = Shader.PropertyToID("Mid"); static readonly int VHigh = Shader.PropertyToID("High"); static readonly int VLevel = Shader.PropertyToID("Level"); static readonly int VPulse = Shader.PropertyToID("Pulse"); void Update() { float bass = analyzer ? analyzer.Bass : 0f; float mid = analyzer ? analyzer.Mid : 0f; float high = analyzer ? analyzer.High : 0f; float level = envelope ? envelope.Value : (source ? Mathf.Clamp01(source.Rms * 3f) : 0f); float pulse = onset ? onset.Pulse : 0f; Shader.SetGlobalFloat(GBass, bass); Shader.SetGlobalFloat(GMid, mid); Shader.SetGlobalFloat(GHigh, high); Shader.SetGlobalFloat(GLevel, level); Shader.SetGlobalFloat(GPulse, pulse); if (vfx != null) { for (int i = 0; i < vfx.Length; i++) { var v = vfx[i]; if (v == null) continue; if (v.HasFloat(VBass)) v.SetFloat(VBass, bass); if (v.HasFloat(VMid)) v.SetFloat(VMid, mid); if (v.HasFloat(VHigh)) v.SetFloat(VHigh, high); if (v.HasFloat(VLevel)) v.SetFloat(VLevel, level); if (v.HasFloat(VPulse)) v.SetFloat(VPulse, pulse); } } if (pulseLight) pulseLight.intensity = lightBase + lightPulse * pulse; if (scaleTarget) scaleTarget.localScale = Vector3.one * (scaleBase + scaleBass * bass); } } ``` `VisualEffect.SetFloat` marks the property as overridden (per the 6000.5 docs), so the value you set wins over the Inspector default. `HasFloat` is used so a graph that does not expose a given name is skipped rather than logging warnings. Global shader floats do not break the SRP Batcher the way per-renderer `MaterialPropertyBlock`s do. ### 8.2 Shader Graph: a pulsing emissive material 1. Create *Assets > Create > Shader Graph > URP > Lit Shader Graph* (or Unlit) named `AudioReactive`. 2. In the Blackboard add **Float** properties with Reference names `_AudioBass`, `_AudioPulse` and `_AudioLevel`. **Uncheck "Exposed"** so they act as globals set from script with `Shader.SetGlobalFloat` (this is how I understand Shader Graph's non-exposed properties; confirm in your editor). 3. Emission: `Emission = BaseColor * (0.2 + _AudioPulse * 4 + _AudioBass * 1.5)`; or drive a `Lerp` between two colours with `_AudioLevel`. 4. Apply to meshes. In Play mode with the binder running the object breathes with the bass and flashes on each onset. ### 8.3 Spectrum as a texture (bars and rings in a shader) A band array is just a 1-D texture. Upload it each frame and sample it with `uv.x` as the frequency axis. ```csharp using UnityEngine; /// <summary>Uploads SpectrumAnalyzer.Bands into a bandCount x 1 float texture as a global (_AudioSpectrum).</summary> public sealed class SpectrumTexture : MonoBehaviour { [SerializeField] SpectrumAnalyzer analyzer; Texture2D _tex; static readonly int GTex = Shader.PropertyToID("_AudioSpectrum"); static readonly int GSize = Shader.PropertyToID("_AudioSpectrumBands"); void Start() { int n = analyzer.BandCount; _tex = new Texture2D(n, 1, TextureFormat.RFloat, false, true) { filterMode = FilterMode.Bilinear, wrapMode = TextureWrapMode.Clamp, name = "AudioSpectrum" }; Shader.SetGlobalTexture(GTex, _tex); Shader.SetGlobalFloat(GSize, n); } void Update() { _tex.SetPixelData(analyzer.Bands, 0); // array length must equal width x height _tex.Apply(false); } void OnDestroy() { if (_tex != null) Destroy(_tex); } } ``` `SetPixelData` requires the array size to equal width x height and match the format (here one float per pixel for `RFloat`), and `Apply` uploads it (both per the 6000.5 docs). In Shader Graph add a non-exposed **Texture2D** property named `_AudioSpectrum`, a **Sample Texture 2D LOD** node (UV = `(uv.x, 0.5)`), and use the R channel as bar height: `step(uv.y, spectrum.r)` draws bars. Bend UVs into polar coordinates for a ring. ### 8.4 VFX Graph: floats, and a spectrum buffer **Floats first.** In the VFX Graph Blackboard add exposed floats `Bass`, `Mid`, `High`, `Level`, `Pulse` (names must match 8.1). Typical hookups: `Pulse` into *Spawn Rate* burst or *Set Velocity* multiplier; `Bass` into *Set Size over Life* multiplier; `High` into *Turbulence* intensity; `Level` into emission colour intensity. **Spectrum per particle.** A structured `GraphicsBuffer` of one float per band lets each particle read its own band (for example `particleId % bandCount`), which is how you get a particle "equaliser." ```csharp using UnityEngine; using UnityEngine.VFX; public sealed class SpectrumVfxBuffer : MonoBehaviour { [SerializeField] SpectrumAnalyzer analyzer; [SerializeField] VisualEffect vfx; [SerializeField] string bufferProperty = "Spectrum"; GraphicsBuffer _buffer; int _id; void Start() { _id = Shader.PropertyToID(bufferProperty); // Structured target; stride must match the struct in the graph (one float here). _buffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, analyzer.BandCount, sizeof(float)); vfx.SetGraphicsBuffer(_id, _buffer); } void Update() { _buffer.SetData(analyzer.Bands); // Re-bind in case the effect re-initialised (the reference is not serialized). vfx.SetGraphicsBuffer(_id, _buffer); } void OnDestroy() { _buffer?.Release(); _buffer = null; } } ``` In the graph: add an **exposed Graphics Buffer** property named `Spectrum`; add a **Sample Graphics Buffer** operator (Operator > Sampling), click its cog and choose **float**, connect the exposed property to its *Buffer* input (the manual says only exposed properties can connect), and feed `Index` from `particleId` modulo the band count (wrap mode can do the modulo). Use the output to scale each particle's size or lift its Y position. VFX Graph packages and Quest support: see [[5.VFX Graph Comparison and Performance]] and the VR section below before committing to VFX Graph in a headset. ## 9. VR and Quest: visualizing live synth input in a headset **Targets.** Quest 2 work uses **Unity 6.3 LTS (6000.3.27f2+)** and the stack in [[2.Quest 2 SDK Stack]] and [[3.Quest 2 Project and Build Setup]]. The note's scripts are plain C#/URP and do not depend on the Unity version, but *VFX Graph on Quest 2 is not verified here.* ### 9.1 Where the synth lives - **Tethered / PC-linked** (Quest 2 as a PC VR display): the interface stays on the PC, `AudioInputTap` and the MIDI services run in the PC build exactly as in [[Eurorack and Unity]], and the headset sees the visuals. This is the realistic way to visualize the Moogs. - **Standalone APK** (sideloaded, as in [[4.Quest 2 Testing and Deployment]]): audio input would come from the headset's microphone (needs the Android microphone runtime permission) or a USB audio device that Unity's `Microphone` API may not enumerate on Android (not verified). Treat "hardware synth into a standalone Quest" as unproven. Fall back to **software audio** (`AudioSourceOutput` mode: clips or the `OnAudioFilterRead` synth), or to **network** control: a PC sends OSC/UDP to the headset ([[Eurorack and Unity]] section 8; OscJack lists most platforms as fine but needs sockets, with a few network-restrictive platforms excluded). ### 9.2 Visualizer ideas that fit VR 1. **Spectrum ring.** Use `SpectrumBars` with bars arranged on a circle around the player, heights from `Bands`. Cheap and legible; a good first test. 2. **Wrist scope.** A `ScopeDisplay` or `LissajousDisplay` on a wrist panel or diegetic terminal ([[6.Diegetic Terminal and Wrist Display]], [[5.Diegetic UI Approaches]]). A `LineRenderer` is a few hundred vertices, fine on mobile. 3. **Room lights.** `Pulse` and `Bass` driving an emissive material and a few *real-time* lights. Baked lights cannot pulse; see [[6.Mobile and Meta Quest Considerations]] in [[Lighting and Baking]]. 4. **Physical interaction.** Let the player grab a Lissajous "orb" and rotate it; or let a controller trigger send a MIDI note back to the Mother-32, closing the loop with [[6.Quest 2 Input Hands and Passthrough]]. 5. **Worked example hook.** Add the spectrum ring and room lights to [[7.Quest 2 Worked Example Room]]. ### 9.3 Mobile VR budget rules - Analyse at **30 Hz** or less on Quest (skip every other frame by checking `Time.frameCount % 2`); use `fftSize = 512`, `bandCount = 16-24`. - No per-frame allocation (every script above allocates only in `Awake`/`Start`). The Quest GC hitch is visible as judder in a headset ([[5.Quest 2 Performance and Rendering]]). - Prefer **shader-driven** motion (global floats, one texture upload) over per-object C# updates, and a few LineRenderers over particle clouds. - Keep the visualization at a comfortable *depth* and avoid strobing: `Pulse` flashes at beat rate can be uncomfortable or unsafe for photosensitive users; clamp the flash rate and amplitude and provide a setting to disable it. ## 10. Scene recipe, pitfalls, Level Up! and patterns ### 10.1 Step-by-step scene 1. Complete [[Eurorack and Unity]] sections 2 and 5 so `AudioInputTap` logs a device and a channel count (or skip it and use a looping `AudioSource` with any music clip). 2. Create `Visualizer Rig`: add `AudioFrameSource` (set Mode to *LiveInput* and assign the tap, or *AudioSourceOutput* and assign the source), `SpectrumAnalyzer` (source assigned, `fftSize` 1024, 32 bands), `EnvelopeFollower`, `OnsetDetector`, `AudioReactiveBinder` (assign the four references). 3. Create `Bars` with `SpectrumBars` (a cube prefab). Press Play, play a note: bars rise. 4. Create `Scope` (LineRenderer + `ScopeDisplay`) and `XY` (LineRenderer + `LissajousDisplay`). Play a sustained note: the scope stands still when the trigger locks. 5. Add an emissive sphere with the `AudioReactive` Shader Graph and the binder: it breathes and flashes. 6. Optional: `SpectrumTexture` plus a bar-shader quad, then `SpectrumVfxBuffer` with a VFX Graph system. 7. Save it as a prefab. For the VR version, build the Quest scene in a 6000.3.27f2+ project and keep the heavy items off. ### 10.2 Pitfalls - **Silence in the visual.** Check `AudioFrameSource.HasData`, then `Rms`. In `AudioSourceOutput` mode the source must be *playing*. In `LiveInput` mode check the tap logged a device and non-zero channels. - **GetSpectrumData and GetOutputData lag.** They read a short history window and are documented as not suited to low latency; the visual follows the sound by tens of milliseconds. That is acceptable for feel, not for tight sync. - **Mixer/mute interaction.** Whether `GetOutputData`/`GetSpectrumData` see the signal before or after a muted mixer group is not verified: test before you mute a source you are analysing. - **Wrong bin maths.** Bin width is `S / N` for `RealFft` with size N, and `S / 2 / samples` for `GetSpectrumData` with `samples` bins. - **Allocations.** `float[]` in `Update` will cause GC spikes. All buffers here are preallocated. - **Smoothing at low frame rates.** Time-based smoothing (`1 - exp(-dt/tau)`) is used so that the look does not change with fps. - **Beat detector too eager.** Spectral flux on full-range bands responds to hi-hat noise; restrict bands. - **Unity timing.** `Update` frames are not synchronised with audio blocks. For musically tight sync (lights on the beat) schedule against `AudioSettings.dspTime` for playback you control, and use MIDI times for hardware you send to. - **Photosensitivity.** See 9.3. ### 10.3 Level Up! tie-ins - **Level 16 - music with style.** Rogers writes about music as part of the game's identity. A visualizer is the *visual twin* of the soundtrack: the same intensity curve that drives [[Music Mood Mixer]] snapshots can drive light and particles, so students can see "tension" rather than only hear it. - **Feedback as design.** Hits and onsets are feedback moments; a short bright `Pulse` on every strong beat teaches the "juice" principle. Have students compare a scene with and without `Pulse`. - **Readability.** Rogers repeatedly stresses that the player must always understand what is happening. A visualizer that overwhelms gameplay fails that test: use `AudioReactiveBinder` scale factors to keep it subordinate. ### 10.4 Game Programming Patterns - **Observer:** `OnsetDetector.Onset` and `EnvelopeFollower.GateOpened` are events; effects subscribe. - **Dirty Flag:** `FrameId` and `Updated` stop recomputing when nothing changed. - **Component:** each visualizer is a small component reading one shared source, not a monolith. - **Double Buffer** (conceptually): `AudioInputTap` copies the newest samples out of the ring into your frame, so analysis never reads while the device writes the same region. - **Object Pool:** if you spawn per-onset particles with `Instantiate`, pool them ([[Interactable Audio]] shows the audio equivalent). See [[Game Programming Patterns (Review)]]. ### 10.5 Exercises 1. Change the `SpectrumAnalyzer` to use `fftSize` 4096 and watch pitch detail improve and transients smear. 2. Add a **peak-hold** bar to `SpectrumBars` (a thin cap that falls slowly). 3. Make `LissajousDisplay` colour shift with `OnsetDetector.Pulse`. 4. Replace `AudioReactiveBinder`'s global floats with `MaterialPropertyBlock`s and measure the SRP Batcher impact in the Frame Debugger. 5. Drive [[Enemy AI State Machine]] alert states from the `EnvelopeFollower` gate: enemies "hear" the loud synth through a microphone, a playful tie to [[Organic Enemy Sensing]]. ## Related (existing) - [[Audio]] - series index - [[Eurorack and Unity]] - `AudioInputTap`, MIDI in/out, OSC, CV caveats - [[FMOD vs Built-in Mixer and Procedural Synth]] / [[2. OnAudioFilterRead Procedural Synth]] - an in-engine synth to analyse - [[Music Mood Mixer]] - the mood signal to visualise - [[Particle Systems and Layered Effects]] / [[5.VFX Graph Comparison and Performance]] - particle and VFX Graph background - [[URP Shaders and Shader Graph]] - the shader side - [[VR]] / [[Meta Quest 2]] / [[0.Choosing a Unity Version]] - VR and Quest context - [[Game Programming Patterns (Review)]], [[Level Up! (Review)]] ## Official docs (index) - `AudioSource.GetSpectrumData` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/AudioSource.GetSpectrumData.html - `AudioSource.GetOutputData`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/AudioSource.GetOutputData.html - `FFTWindow`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/FFTWindow.html - `LineRenderer.SetPositions`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/LineRenderer.SetPositions.html - `Texture2D.SetPixelData`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Texture2D.SetPixelData.html - `VisualEffect.SetFloat`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/VFX.VisualEffect.SetFloat.html - `VisualEffect.SetGraphicsBuffer`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/VFX.VisualEffect.SetGraphicsBuffer.html - VFX Graph Sample Graphics Buffer (17.5 manual): https://docs.unity3d.com/Packages/[email protected]/manual/Operator-SampleBuffer.html See also (added 2026-11-13): [[MIDI Rhythm Game]] - a beat-synced note highway that can sit on top of these visuals; [[Compute Shaders and GPU Instancing]] - a GPU boids swarm whose speed follows AudioFrameSource. ## In this folder <!-- folder-list:start --> <!-- generated by pubprojects_weblists.py: edits inside this region are replaced on the next run --> *No notes in this folder are published yet.* <!-- folder-list:end -->