Engineering / KeyTone

Building a low-latency macOS keyboard sound engine in Swift. Without Accessibility permissions.

KeyTone is a free macOS menu-bar app that plays mechanical-keyboard recordings as you type, whichever app is in front. The job sounds simple: hear a key go down, play a click. But the click has to arrive while it still feels like part of the keystroke, and the app has no reason to know what you wrote. Those two constraints shaped the engine more than anything else.

By Ravix Studio

Listen without taking control.

Input Monitoring is still a system permission. We ask for it because KeyTone needs events outside its own app. What we don’t ask for is Accessibility: the engine doesn’t need to inspect another app’s interface, change an event, or inject one. It uses a Core Graphics session event tap with .listenOnly, scoped to key-down, key-up and modifier changes.

There are two separate boundaries here. macOS grants permission to observe input; KeyTone’s handler decides what to do with that input. We use the macOS virtual key code as a physical-key identifier for sound selection, not as a character. A key code could be interpreted using a layout and modifier state, but the app does not do that translation or assemble a text stream. It doesn’t store or send keystrokes. When macOS withholds keyboard events under Secure Input, there’s nothing for the engine to play.

Permission and tap health aren’t the same thing. On launch we preflight access, request it if needed, and poll while waiting for approval. Once installed, the tap sits on the main run loop; the callback re-enables it if macOS reports a timeout or user-input disable. That’s another reason not to put audio-file work in the handler. It’s on the same run loop the app uses for its UI.

Sources/main.swift · waitForInputMonitoring, startMonitoring, handle

Play the key, not the letter.

A physical press and its release are two events with different sounds. We ignore repeated key-down events from a held key, so the keyboard’s repeat setting doesn’t turn one press into a burst of clicks. Modifiers come through as flagsChanged instead. The handler uses a table from key code to modifier flag and tests whether that flag is set. It’s a deliberately simple model: left and right Shift share a flag, so it’s not independent left/right switch tracking when both are held.

The engine doesn’t need a recording for every key. A typical pack has generic recordings for rows, plus dedicated recordings for Space, Enter and Backspace. The mapping gives ordinary keys a stable variation in row choice and pitch derived from the key code. Nearby keys needn’t sound identical, but a given key has a consistent baseline. Stabilized keys use their own recording at its original base pitch; Shift borrows Enter. If a requested recording is missing, the lookup falls back within that same press or release set. A custom pack with no release recordings can play presses without inventing a release.

Spatial Audio here means stereo pan, not head tracking or a 3D model. We spread each ANSI row from left to right, center Space, and scale the pan to 80% of its full range. A few extra key codes map to nearby positions; an unknown one plays centered. That’s enough to put the sound roughly under your fingers, but it’s not a geometry model of every keyboard.

let pan = flag("spatial") ? (KeyLayout.pan[e.keyCode] ?? 0) * 0.8 : 0
let v = KeyLayout.voice(e.keyCode)
player.play(v.name, down: down, pitch: v.pitch, pan: pan, vary: flag("randomPitch"))

Sources/main.swift · handle; Sources/SoundPack.swift · KeyLayout, samples

Prepare the recordings before anyone types.

KeyTone ships with ten recorded packs and reads custom packs from its Sounds folder in Application Support. A folder is a pack; press and release are separate banks. At load time, we decode to mono floats at 44.1 kHz and cap the source clip at 150 ms, fading it out if a cut is needed. The loader only opens regular files and bounds how much audio it reads as well as the accepted sample rates and channel counts. A directory someone drops into the app is input, not a trusted bundle of assets.

The beginning of the recording matters as much as the speed of the engine. A buffer can be scheduled promptly and still sound late if its initial samples are silence. The sound-pack notes call out trimming leading silence when preparing the bundled assets. That isn’t something the runtime trim function does: it caps the tail. For a custom pack that sounds late, listen to the original clip before tuning playback.

We match the recordings by RMS around the strongest part of each clip, rather than matching a single peak. The generic presses set the reference when present. Dedicated presses are matched 1.5 dB above that reference and releases 6 dB below it; then the whole pack is scaled to a common peak. Those offsets are mix choices, not measurements of how much louder a real space bar is. The goal is to hear the different character of the large keys without making them dominate the mix.

Sources/SoundPack.swift · init, loudness, trim, readMono; Sources/main.swift · scanPacks

Spend memory to keep playback simple.

When you pick a sound pack, the player builds a bank of PCM buffers keyed by press or release and recording name. It renders 31 pitch steps for each resolved entry up front with a linear-interpolation resampler. Faster playback raises pitch and shortens the sound; those two effects aren’t separated. We keep that compromise for these short recordings rather than adding a real-time pitch-shifting stage.

On the normal event path, we choose the closest prepared pitch and schedule its buffer. Natural Variation jitters the pitch ratio by up to 1.5% on each event, before snapping to a bucket, and chooses a gain from 75% to 100% on the voice. Gain is our stand-in for strike force. We don’t measure how hard someone pressed the key. Turn variation off and the same physical key gets its fixed pitch and full voice gain again.

The engine connects 16 AVAudioPlayerNodes to an AVAudioEngine mixer. Each event takes the next voice in a ring. A release can overlap a press, and the sound of one key can decay underneath the next. If the ring wraps while a voice is still playing, the new click interrupts it. The pool puts a fixed bound on playback voices; it doesn’t guarantee every tail will finish.

let voice = voices[nextVoice]
nextVoice = (nextVoice + 1) % voices.count
voice.pan = pan
voice.volume = vary ? Float.random(in: 0.75...1) : 1
voice.scheduleBuffer(variants[i], at: nil, options: .interrupts)

The cost moves to pack selection and memory: the bank holds multiple rendered copies of the clips. The benefit is that a normal keystroke doesn’t open a file, decode audio, resample it, or build an engine graph. That’s what we mean by low-latency design, not a claim about a measured key-to-speaker delay. The tap runs on the main run loop, and scheduling a buffer is not the same as hearing it. A meaningful end-to-end measurement would need to capture a physical strike and the resulting sound on the same recording, with the output device stated.

Sources/main.swift · Player.init, Player.load, Player.play; Sources/SoundPack.swift · resample

Keep playing when the output changes.

A hot audio graph helps until you unplug the headphones. KeyTone can follow the system’s default output or remember a chosen device by its UID rather than its current device ID. If the chosen device isn’t available, it falls back to the system default. On a route switch, it stops the voices and engine, switches the output unit’s device, and reconnects the mixer without forcing an output format so the new device’s format can take over.

Graph recovery is part of playback, not just setup. The app listens for engine configuration changes, rebuilds the output connection on wake or session reactivation, and tries to start the engine from play if it finds it stopped. That last check is the exception to the fast path. It’s better to try to recover than to silently keep scheduling into a stopped engine.

Sources/main.swift · AudioOutput, Player.start, Player.route, Player.restart, recoverFromSleep

Ship an app that can update itself.

The build script runs a sound-pack self-test before assembling the app. It invokes swiftc directly for arm64 and x86_64, targeting macOS 14, then uses lipo to produce one universal executable. We bundle Sparkle, pin its downloaded archive by checksum, and sign its nested code before signing the app with the hardened runtime enabled.

Signing matters even before distribution. Input Monitoring can stop working after an ad-hoc rebuild or a change of signing identity. A stable development certificate keeps the permission from becoming a recurring setup problem. For releases, the DMG script uses Developer ID, signs the disk image, submits it to Apple for notarization, staples the ticket and assesses the result with spctl.

Sparkle adds a separate check from Apple’s signing and notarization. The app has a public EdDSA key and uses the appcast to discover updates; the release process signs the update download with the matching private key. The build number is what Sparkle compares. Our release checklist puts the appcast up last so the update it advertises is already downloadable. The small app still needs a release process where the permission, the download, and the next update keep working together.

build.sh · self-test, universal build and signing; make-dmg.sh · Developer ID and notarization; Sources/main.swift · Sparkle updater; KeyTone release notes · appcast

Do less when the key goes down.

KeyTone works by making the per-event job small: observe without controlling, pick a prepared sound without looking at text, and keep enough voices ready for the next key. The work we moved out of that path still matters. Recording preparation, device recovery and release signing are what make the short handler useful in an app people can actually install.