- Swift 100%
|
|
||
|---|---|---|
| Audio Visualizer | ||
| AudioVisualizer.xcodeproj | ||
| AudioViZLS.icon | ||
| AudioViZLSTests | ||
| .gitignore | ||
| AboutWindow.swift | ||
| AnalysisChunker.swift | ||
| AUDIO_SOURCE_SWITCHER.md | ||
| AudioSourceManager.swift | ||
| AudioSourcePicker.swift | ||
| AudioViZLS-Info.plist | ||
| AudioViZLS.entitlements | ||
| ContentView.swift | ||
| DebugView.swift | ||
| MicrophoneAudioEngine.swift | ||
| PERMISSIONS.md | ||
| ProcessTapAudioEngine.swift | ||
| README.md | ||
| SYSTEM_AUDIO_SETUP.md | ||
| SystemAudioEngine.swift | ||
Audio Visualizer
A small, frugal music visualizer for Apple platforms, written in SwiftUI. It listens to the audio playing on your Mac (or to the microphone) and draws it as a live frequency spectrum.
- One codebase for macOS, iOS, iPadOS and visionOS
- No installs: no audio driver, no extension, no routing in Audio MIDI Setup
- Frugal by design: one analysis pass per audio chunk, one draw per frame, and no timer at all while it is silent
Audio sources
Which sources are offered depends on the platform. The app starts with the first available one in this order:
| Source | Platforms | How it works | Permission |
|---|---|---|---|
| System Audio | macOS 14.2+ | Core Audio process tap on a private aggregate device | System Audio Recording |
| Screen Capture | macOS 13+ | ScreenCaptureKit audio stream (fallback for macOS 13 to 14.1) | Screen Recording |
| Microphone | macOS, iOS, iPadOS, visionOS | AVAudioEngine with an AVAudioSinkNode |
Microphone |
On iOS, iPadOS and visionOS the system does not allow capturing the audio of other apps, so the microphone is the only source there. On macOS 12 it is the only one as well.
More details: SYSTEM_AUDIO_SETUP.md, AUDIO_SOURCE_SWITCHER.md and PERMISSIONS.md.
Visualizers
| Visualizer | Description |
|---|---|
| Spectrum | Classic frequency bars with a rainbow gradient. Runs on the graphics card with Metal. |
| Mirror | Bars that grow up and down from a line in the middle, over the whole width of the window, with the bass in the middle and the highs at both edges. Runs on the graphics card with Metal. |
| LED | Segmented level meter like a hi-fi system, with white peak markers that fall slowly. Runs on the graphics card with Metal. |
| Waveform | The contour of the spectrum as a line with a soft glow, mirrored above and below the middle. Runs on the graphics card with Metal. |
| Circular | Spectrum bars arranged in a ring, like the classic iTunes visualizer, with a soft glow. A picture of your own can be put in the middle (see the settings below). Runs on the graphics card with Metal. |
| Rings | Three concentric rings that pulse with the bass, the mids and the treble |
| Blob | A soft closed shape whose edge follows the spectrum |
| Kaleidoscope | A rotating, color-cycling flower in the spirit of early 2000s music player visualizers |
| Vortex | A twisting tunnel of rings that flies towards you, in the same spirit |
| Lissajous | An oscilloscope figure that turns with the mids and breathes with the bass, with a soft trail |
| Starfield | A flight through stars that speeds up with the bass |
| Fireworks | Bursts of sparks that go off with the beat |
| Echo | A mirrored frequency ring whose afterimages swell and turn away into a tunnel |
| Aurora | Three slow ribbons of light that wave with the bass, the mids and the treble, with a soft smear |
| Strings | A bundle of trembling strings that spread from a fuzzy core, over a pastel haze |
| Flow | A feedback picture in the spirit of the old players (and of the visualizers in Apple's Music app, which work with a greyscale buffer, a palette, a warp field and a Gaussian blur): a ring that follows the spectrum is drawn into a picture that is zoomed outwards, turned and swirled, softened and dimmed every frame. The beat flashes the middle, and every 16 beats or 24 seconds a new random scene with a different direction of turning, swirl and colors eases in. Runs on the graphics card. |
| Classic | The psychedelic one, in the spirit of the classic visualizer of the Music app. It uses the same technique as Flow (a picture of brightness values with a memory, a palette, a warp and a blur), but with nine looks that take turns every 16 beats or 24 seconds, never the same twice in a row. A look is made of what is drawn (braiding sine waves, ellipses that swell, rays from the middle, or a line that opens up and down), how the old picture is pushed around (a field like smoke, a stream sideways, or ripples running outwards), how fast it turns, zooms and swirls, how long the trails stay, and a palette (bands of the hue circle, fire, or two colors running into each other). The numbers ease over and the palette fades, so nothing jumps. Runs on the graphics card. |
| Music | A test of the other way to build such a picture, after the principles of the fluid visualizer of the Music app: a picture with a memory, a field that pushes it around, fading, and a palette at the end. Here the parts change one by one and each at its own time instead of as a fixed look: what is drawn (waves, ellipses, rays, a line that opens up), the field (smoke, stream, ripples, flower, whirlpool), the movement (tunnel, smear, spin, calm) and the colors, which stay in one family for a good while, fade over slowly and are partly cut into steps like contour lines. Runs on the graphics card. |
| Terrain | A mountain range made of the spectrum. Its peaks melt downwards in a soft smear, like the pixel visualizers of the early 2000s. Runs on the graphics card with Metal. |
| Surface | The spectrum as a rippling surface that flies away from you, dithered, with a line of dots on the front edge. Runs on the graphics card with Metal. |
Terrain and Surface work on a small grid of brightness values that is changed a little with every frame (let it sink or shrink, soften it, dim it) while the new sound is drawn on top. What was drawn earlier stays as a trail. The grid is stretched over the window by the graphics card, so a large window costs next to nothing and resizing does not stutter. Where Metal cannot be used, the same pictures are made on the processor (PixelField).
The height profile family
Spectrum, Mirror, Waveform, Circular, LED, Terrain and Surface show the same thing, one height for every frequency band, in seven styles. They share one renderer (PixelRenderer), one set of numbers that describes how the profile looks (ProfileLook, with ProfileMorph moving it from one style to another), one height for the loudest band (85 % of the window, half of it each way for Mirror and Waveform, only Surface stands lower, at 45 %, because its picture is built in perspective) and one palette for LED, Terrain and Surface (ProfilePalette, chosen with the Color scheme setting: Meter, Fire, Ocean, Neon or White). Spectrum and Mirror keep their rainbow, Waveform its purple to green. Switching between them is not a fade, the one turns into the other:
- Spectrum → LED: the thin bars draw together in groups, each group to the middle of one wide bar. The bars take over its height, get as wide as it and turn from the rainbow to the meter colors. Then the cuts that make the blocks go over the bars from the left to the right. When LED is complete, its white peak markers fall in from above the picture, one after the other, at random times. LED → Spectrum goes the other way: the markers fall onto the bars, the cuts leave from the left to the right, and the wide bars draw apart.
- Terrain ↔ Surface: Terrain sinks to the lower height of Surface while the dotted line of Surface fades in on its edge. When it has arrived, the sound flows into Surface at once and what is left of Terrain runs out. The other way round, Surface rises while its line fades out.
- Terrain or Surface ↔ LED: the picture turns into a mosaic with cells as big as the blocks of LED, keeps running and fades out while the bars come in. The other way round, the picture gets finer as the bars fade.
- Spectrum → Mirror: the spectrum is squeezed into the right half of the window while its mirror image is revealed on the left, so that the bass ends up in the middle and the highs at both edges. At the same time the middle line comes: the bars grow up and down from it, with half of the height each way. Mirror → Waveform: first the bars unfold back to the order of the spectrum, then they are cut away from below until only a short piece at the top is left, they fade, and the line takes over along the contour. The other way round it is the same backwards. Spectrum → Circular: first the baseline is lifted from the bottom edge to the height where the ring will have its bottom, with the bars shrinking to the length they have on the ring. Then it rolls up: the row of bars bends into an arc, which turns a little as it curls (so that the first bar ends up at the top), and the arc closes to a ring around the middle of the window with the bars pointing outwards. Back, the ring opens and unrolls first, then the baseline goes down. Mirror and Waveform go to the ring and back the same way, directly: in the first step they unfold and are lifted at once (Mirror loses its fold and its lower half, Waveform its line and gets its bars), so they do not stop at Spectrum on the way. The picture in the middle of the ring (see the settings) comes in when the ring has closed, and goes at once when it opens.
- Spectrum ↔ Terrain or Surface: the bars fade and their gaps close while the picture takes the sound.
Switching between visualizers
When you switch to another visualizer outside the family, the old one plays out (it gets a spectrum that dies down) while the new one builds up from silence, and one fades into the other. With Reduce Motion turned on in the system settings the app switches at once.
On iOS, iPadOS and visionOS tap the gear icon to open the controls. On macOS they live in the menu bar:
- The Visualizer menu lists the audio sources and the visualizer styles with a checkmark on the active one, and has switches for Keep Moving in Silence and Float Above Other Windows.
- Settings… (⌘,) in the app menu opens the full panel with the sliders in the middle of the window. It is a child window of the main window: it moves with it, centers itself again when you resize the window and stays open when you click into the window. Esc, its close button or ⌘, close it.
The panel lets you pick the source and the visualizer, and adjust the settings. On macOS it has four tabs, Visualizer (source, the visualizers as a grid, random mode), Sound (sensitivity, upper frequency, varying the profile), Display (color scheme, frame rate, keeping moving in silence, the picture for Circular) and Window (background, floating, debug info), with the label of a setting on the left and its control on the right. On iOS, iPadOS and visionOS it is one list:
- Sensitivity lifts the quieter bars, which helps with weak signals such as the microphone.
- Upper frequency starts at the highest frequency, where nothing is cut off. Many songs have no music above 16 kHz or even 12 kHz (compressed audio is cut off there), and what is left up there is a steady level: every band has the same height, which shows as a flat block at the end of a row of bars or a dull rim at the end of a ring. Moving the slider to the left cuts the top off, and the rest is stretched over the whole width, so a ring stays closed. It works for all visualizers. The frequency shown is about right: the bands run to half the sample rate, 24 kHz at 48 kHz.
- Random mode changes to another visualizer by chance, after a time that is also chosen by chance between two limits (Shortest and Longest, 5 seconds to 5 minutes). All visualizers come up before one comes up again, and it never picks the one that is shown. A visualizer that is added to the app later takes part without any change. Choosing one yourself starts the time again. On macOS the Visualizer menu has a switch for it too.
- Color scheme sets the colors of LED, Terrain and Surface from the bottom to the top: Meter (green, yellow, red), Fire, Ocean, Neon or White.
- Vary the profile loosens the shape of the spectrum by chance. In most music the bass is by far the strongest part, so the bars almost always fall off from the left to the right. With this on, Perlin noise lets the strong and the weak parts of the spectrum wander about, the quiet parts are lifted and the highs get some more room. The loudest band keeps its height. It works for all visualizers. The strength can be set, and it is off by default.
- Keep moving in silence decides whether Kaleidoscope and Vortex keep drifting when no audio plays. If you turn it off, they begin to slow down as soon as it gets quiet.
- Slow down after sets how many seconds of silence pass before they ease to a standstill (5 seconds to 5 minutes). Playing audio gets them moving again gently.
- Circular: picture in the middle is tucked away in a folded section at the bottom of the panel. Choose picture… takes any picture, makes it smaller (at most 1024 pixels) and keeps it in the application support folder. Circular then shows it inside the ring, cut to a circle, like on the cover of a music video, and the ring moves a bit further out to make room. A round preview lets you choose which part of the picture shows: drag the picture to move it, and zoom with the slider (up to four times). A new picture fades in over the old one, and Remove lets the picture fade out and goes back to the plain ring.
- Frame rate is Auto, 60 or 30. (The visualizers on the graphics card, which are Spectrum, LED, Flow, Terrain and Surface, follow the display: Auto draws at its full refresh rate, 60 and 30 take a whole number of refreshes as close to that as they get. On macOS 14 and later their timer follows the window to the display it is on.) For the other visualizers, Auto reads the refresh rate of the display the window is on and takes a whole number of refreshes as close to 60 frames as possible (60 on 60 and 120 Hz, 72 on 144 Hz, 55 on 165 Hz), so every frame stays on screen equally long. It follows the window to another display. A fixed 60 or 30 draws exactly that many frames, which only stays even on displays whose rate is a multiple of it.
On macOS there are two more settings for the window:
- Background opacity fades the black background away, so only the visualizer stays and floats on your desktop. At 100 % the window looks as usual.
- Float above other windows keeps the window on top, which suits a see-through overlay.
All settings are saved per device.
Adding a visualizer takes three steps: implement the Visualizer protocol (one render method that draws into a GraphicsContext), add a case to VisualizerType and return the new class from makeVisualizer().
Debug builds
A debug build knows a few launch arguments (Edit Scheme → Run → Arguments), none of them is part of a release build:
-syntheticSpectrumfeeds a made-up music spectrum instead of real audio, which is useful in the simulator, where there is no audio input.-syntheticPlateau(together with-syntheticSpectrum) leaves nothing but a flat level above the middle of the spectrum, like a song that is cut off at 13 kHz.-randomVisualizersswitches the random mode on with short times (8 to 14 seconds) and writes every change to the console, which is useful for finding changes that look wrong.-allTransitions 10goes from every visualizer to every other one exactly once (306 changes, 307 steps with the first), staying 10 seconds on each (the number is optional), and writes every step to the console, for looking at all changes.-showAbout(macOS) opens the About window when the app starts.-cycleProfilegoes through Spectrum, Mirror, Waveform, Spectrum, LED, Terrain, LED, Surface and LED, 12 seconds each, to look at the changes between them. A debug app that was started from Xcode's device tools may be stopped by the tools after about two minutes.-cpuVisualizersdraws Spectrum, LED, Terrain and Surface on the processor, to compare them with the graphics card.-slowTransitionstretches the change from one visualizer to the next, so it can be looked at: 9 seconds between visualizers of different families, 7.5 seconds within the height profile family.-alternateTerrainAndSurfacechanges between Terrain and Surface every 6 seconds, to look at the change between them.-selectedVisualizer Terrainstarts with that visualizer. Note that it overrides the saved choice, so the picker cannot change it while the argument is given.
The pixel visualizers also write their real frame rate to the console every two seconds.
How it works
Audio source (tap, ScreenCaptureKit or microphone)
↓ mono samples
AnalysisChunker collects samples into equal chunks of 960 frames
↓
AudioAnalyzer 2048-point FFT, Hann window, dB scale, 512 bands, smoothing
↓ [Float] with 512 values from 0 to 1
AudioSourceManager switches sources, reports silence, pauses in the background
↓
SpectrumData holds the latest spectrum, publishes nothing
↓
VisualizerView SwiftUI Canvas on a steady timer (auto, 60 or 30 fps), stops when silent
Some design notes:
- The analyzer scales every spectrum to its own maximum, so the tallest bar always reaches the top. Quiet and loud input look alike apart from the noise floor.
- A configurable silence threshold keeps faint noise from being stretched to full height. The microphone uses a hard gate. The system sources (tap and Screen Capture) use a soft one: below a peak of 0.006 they count as silence, between 0.006 and 0.03 the bars grow smoothly from zero, and above that nothing changes. A stream or page that is open but plays nothing audible therefore stays calm. The values live in
AudioAnalyzer.forSystemAudio()andMicrophoneAudioEngine. - Every source hands the analyzer the same chunk size, so all sources look alike.
- Because every spectrum is scaled to its own maximum, the absolute loudness is lost. Beat detection (Flow, Fireworks) therefore needs the level of the bass in decibels from before the scaling. The analyzer appends it as a 513th value, and
SpectrumDatasplits it off again (bassDecibels). - The analyzer's 512 bands are spaced linearly (about 47 Hz each), so the whole bass range sits in the first few bands. Newer visualizers call
VisualizerSupport.logBandsto regroup them by musical pitch. Spectrum, Waveform and Circular still use the linear bands (LED, Terrain and Surface use the logarithmic ones, so a change between Spectrum and LED also changes which frequency a bar shows). - The spectrum changes about 50 times per second and lives in its own object,
SpectrumData, which publishes nothing: the visualizer reads the latest values when it draws a frame. TheAudioSourceManagerpublishes only what changes rarely (source, status, silence), so the window, the menu and the settings panel are not refreshed while music plays. The engines report to the manager with plain callbacks, and the code uses no Combine pipelines.ObservableObjectstays for now, because its replacement@Observableneeds iOS 17 and macOS 14. - Visualizers draw with as few paths as possible (one fill or stroke for all bars). One steady timer draws every frame, with the latest spectrum, at an even pace that fits the display (see the frame rate setting). It runs at 30 frames while it is silent, because the picture then changes slowly, and it stops when the last sound is a few seconds past: after three seconds for most visualizers, so the falling LED peak markers can finish, and after the slow-down for Kaleidoscope and Vortex. A stopped timer costs nothing and leaves the last image on screen. Kaleidoscope and Vortex keep drifting in silence so they never look frozen. After a configurable delay (30 seconds by default) they ease down to a standstill over a few seconds. The next sound starts the timer again and speeds them up just as gently.
Requirements
- Xcode 27 or later
- Deployment targets: macOS 12, iOS 15, iPadOS 15, visionOS 1 (the minimums Xcode 27 supports). Newer APIs are guarded with
#available.
Build and run
- Open
AudioVisualizer.xcodeprojin Xcode. - Select the
AudioViZLSscheme and a destination. - In Signing & Capabilities, choose your own team. The bundle identifier is
de.user1337.AudioVisualizer, change it if needed. - Run. Allow the permission dialog for the source you use.
The Show debug info setting (off by default) adds a small overlay with the current source and the amplitudes, which helps when tuning for a new device or source.
Tests
The AudioViZLSTests target uses Swift Testing and has no host app: it compiles only the logic files (analyzer, chunker, frame timing, eased speed, visualizer support, spectrum data, audio features, the scene director of Flow, spectrum variation and trim, pixel grid, the looks and changes of the height profile family, panel layout). The tests run without starting the app and without touching audio, so they are quick and need no permissions.
- Select the
AudioViZLSTestsscheme and My Mac as destination. - Press ⌘U.
The analyzer tests compare against reference values recorded before the analyzer was reworked, so a change of its output shows up. The panel layout tests are macOS only and are left out on other destinations.
Project layout
AudioVisualizer/
├── Audio Visualizer/ App entry point, analyzer and visualizers
│ ├── AudioVisualizerApp.swift
│ ├── AudioAnalyzer.swift
│ ├── Visualizer.swift Protocol for all visualizers
│ ├── VisualizerType.swift List of visualizers and their factory
│ ├── VisualizerView.swift Canvas host, applies the sensitivity
│ ├── SpectrumData.swift The current spectrum, apart from the rest of the state
│ ├── DisplayRefreshRate.swift Refresh rate of the display, frame intervals that fit it
│ ├── VisualizerSupport.swift Shared colors, logarithmic bands, band levels
│ ├── SpectrumVisualizer.swift One file per visualizer: Spectrum, MirrorBars, LEDBars,
│ ├── ... Waveform, Circular, Rings, Blob, Kaleidoscope, Vortex,
│ │ Lissajous, Starfield, Fireworks, Echo, Aurora, Strings, Terrain, Surface
│ │ (Spectrum and LED draw on the graphics card, these files are the fallback)
│ ├── Trail.swift Recent shapes drawn faded behind the current one
│ ├── PixelField.swift Pixel grid of Terrain and Surface on the processor (fallback)
│ ├── PixelShaders.swift The Metal shaders of the height profile family: Terrain, Surface, and the bars
│ ├── PixelRenderer.swift Runs the shaders: two grids, one step per frame, the bars of Spectrum and LED
│ ├── ProfileMorph.swift Looks of the four styles, the changes between them, the palette
│ ├── ProfileBars.swift Heights of the bars, peak markers, and how they fall in and out
│ ├── FeedbackRenderer.swift Flow: the feedback picture on the graphics card
│ ├── FeedbackShaders.swift The Metal shaders of Flow
│ ├── FlowDirector.swift Random scenes for Flow, switched by the beat
│ ├── AudioFeatures.swift Smoothed levels and beat detection, used by Flow and Fireworks
│ ├── SpectrumTrim.swift The upper frequency setting
│ ├── RandomShuffle.swift The random mode: which visualizer comes next and when, and the walk through all changes
│ ├── CircularCenterImage.swift The picture in the middle of Circular: reading, shrinking, keeping, crop and fade
│ ├── CircularCenterOverlay.swift Draws that picture over the ring of the shader
│ ├── CircularCropEditor.swift The round preview in the settings for choosing the part of the picture
│ ├── SpectrumVariation.swift Varying the profile with Perlin noise
│ ├── MetalPixelView.swift Hosts the Metal views, with their own display link on macOS 14+
│ ├── WindowAppearance.swift macOS only: see-through window and floating level
│ ├── VisualizerCommands.swift macOS only: the Visualizer menu and Settings… in the menu bar
│ ├── CenteredSettingsPanel.swift macOS only: the settings panel as a child window, centered
│ ├── SettingsPanelContent.swift Source, visualizer and all options (the list on iOS, the tabs on the Mac)
│ ├── MacSettingsView.swift macOS only: the settings in four tabs
│ ├── ControlsView.swift
├── AudioSourceManager.swift Source selection and lifecycle
├── AudioSourcePicker.swift
├── AnalysisChunker.swift
├── ProcessTapAudioEngine.swift System Audio (macOS 14.2+)
├── SystemAudioEngine.swift Screen Capture (macOS 13+)
├── MicrophoneAudioEngine.swift Microphone
├── ContentView.swift
├── DebugView.swift
└── AudioViZLSTests/ Unit tests (Swift Testing), see Tests
Known limitations
- The minimum OS versions are covered by the compiler's availability checks, but the app has not been run on macOS 12 or iOS 15 yet.
- The microphone gate was tuned on an iPhone 13 mini. A noisier device may need a higher
silenceThresholdinMicrophoneAudioEngine.swift.