Skip to Content
macos-media-keys

πŸŽ›οΈ Usage

The sendMediaKey function, the five media keys it accepts and how errors are reported.

The package has a single named export and a single type. It is ESM only and needs Node.js 20 or later.

import { sendMediaKey, type MediaKey } from "@kud/macos-media-keys"

sendMediaKey(key)

sendMediaKey(key: MediaKey): Promise<void>

Posts a system media key to whichever app is responding to media keys. The promise resolves once the key press has been delivered and rejects with an Error otherwise. There is no return value and nothing to configure.

await sendMediaKey("play") // play/pause toggle
await sendMediaKey("next")
await sendMediaKey("previous")
await sendMediaKey("forward") // fast-forward within the track
await sendMediaKey("rewind")

MediaKey

type MediaKey = "play" | "next" | "previous" | "forward" | "rewind"
KeySystem keyEffect
playNX_KEYTYPE_PLAYToggles play and pause
nextNX_KEYTYPE_NEXTSkips to the next track
previousNX_KEYTYPE_PREVIOUSSkips to the previous track
forwardNX_KEYTYPE_FASTFast-forwards within the track
rewindNX_KEYTYPE_REWINDRewinds within the track

play is a toggle, not a play command: if nothing is playing, it starts the last active player; if something is, it pauses it.

Error handling

sendMediaKey rejects in three situations.

SituationMessage
Not running on macOS@kud/macos-media-keys only works on macOS
Accessibility permission missingnot authorized β€” grant your terminal Accessibility access in System Settings β†’ Privacy & Security β†’ Accessibility
The helper fails without outputfailed to send media key: <key>
try {
  await sendMediaKey("next")
} catch (error) {
  console.error((error as Error).message)
}

The helper's own message is passed through when it has one, so the permission text above comes straight from the native side. See Permissions for how to resolve it.

An unknown key name is a type error in TypeScript. From plain JavaScript it reaches the helper, which prints its usage line and the promise rejects with that text.

Command line

If you would rather call it from a shell, macos-media-keys-cli wraps this library.