How can I use Python’s MPNowPlayingInfoCenter to get current song information from Mac OS?

  Kiến thức lập trình

I am attempting to write a daemon in Python that will push the artist and title of the song that I’m currently playing into my Slack status. I previously used MPRIS to do this in Linux, and WinRT for the same functionality in Windows. Now I’m on a Mac and coming up against a wall.

I can see that the data that I want is in the Control Center.

I found a program called nowplaying-cli that correctly outputs the track’s data to the command line.

nowplaying-cli get artist title
PJ Harvey
A Noiseless Noise

I’m sure if I had to, I could somehow call this program from my Python script and parse its output into the data I want. But that adds another dependency that I’d rather avoid.


I found this StackOverflow answer that discusses using Python’s Objective C bindings to write to the Now Playing object, which would theoretically push any data I wanted into the Control Center. I’ve pulled in the relevant code to obtain the nowPlayingInfo object, but I haven’t been able to figure out how to actually get any useful data from that object.

info_center = MPNowPlayingInfoCenter.defaultCenter()
nowplaying_info = info_center.nowPlayingInfo

I’ve tried all of the introspection methods I could find to check for built-in attributes and methods that I could use to get the artist and track (e.g. getattr(nowplaying_info, MPMediaItemPropertyArtist)) but all I got were error messages that the artist attribute doesn’t exist on that object.

The Apple Developer docs for nowPlayingInfo don’t appear to shed much light on how to grab data from it.

Any insight on how to accomplish this would be much appreciated!

LEAVE A COMMENT