Recreating OS X media keys on the command line

2 min read Original article ↗
  • Recreating OS X media keys on the command line

    Place this at ~/mediakeys.scpt (download):

    on run argv
        if (count of argv) is greater than 0 then
            set theCommand to item 1 of argv
        else
            set theCommand to ""
        end if
        
        set systemVolume to (output volume of (get volume settings))
        
        if theCommand is equal to "-" then
            set volume output volume systemVolume - 5
        else if theCommand is equal to "--" then
            set volume output volume systemVolume - 10
        else if theCommand is equal to "+" then
            set volume output volume systemVolume + 5
        else if theCommand is equal to "++" then
            set volume output volume systemVolume + 10
        else if theCommand is equal to "mute" then
            set volume output volume 0
        else if theCommand is equal to "unmute" then
            set volume output volume 45
            
        else if appIsRunning("Rdio") then
            tell application "System Events"
                if theCommand is equal to "n" or theCommand is equal to "next" then
                    tell application "Rdio" to next track
                else if theCommand is equal to "p" or theCommand is equal to "previous" then
                    tell application "Rdio" to previous track
                else
                    tell application "Rdio" to playpause
                end if
            end tell
            
        else if appIsRunning("iTunes") then
            tell application "System Events"
                if theCommand is equal to "n" or theCommand is equal to "next" then
                    tell application "iTunes" to next track
                else if theCommand is equal to "p" or theCommand is equal to "previous" then
                    tell application "iTunes" to previous track
                else
                    tell application "iTunes" to playpause
                end if
            end tell
        else
            beep
        end if
    end run
    
    on appIsRunning(appName)
        tell application "System Events" to (name of processes) contains appName
    end appIsRunning

    …and alias it:

    alias m="osascript ~/mediakeys.scpt"

    Supports iTunes and Rdio, whichever is open. Available commands:

    • m to play or pause
    • m n or m next for next track
    • m p or m previous for previous
    • m + / m ++ to increase system volume by 5 or 10%
    • m - / m -- to decrease