0

I'm developing my first app on python for OS X (and also generally on python) and i faced the problem… My current script parses sounds from iTunes and prints it in to the window. It looks like this

from Cocoa import *
from Foundation import *
from ScriptingBridge import *

class SocialTunesController(NSWindowController):
    testLabel = objc.IBOutlet()

    def windowDidLoad(self):
        NSWindowController.windowDidLoad(self)
        self.updateTrack()

    def updateTrack(self):
        iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
        current_track_info = "Name: " + iTunes.currentTrack().name() + "\nArtist: " + iTunes.currentTrack().artist() + "\nAlbum: " + iTunes.currentTrack().album()
        self.testLabel.setStringValue_(current_track_info)

if __name__ == "__main__":
    app = NSApplication.sharedApplication()

    viewController = SocialTunesController.alloc().initWithWindowNibName_("SocialTunes")
    viewController.showWindow_(viewController)

    from PyObjCTools import AppHelper
    AppHelper.runEventLoop()

The main problem is how to fire event when track is changes that it automatically would update the track info in current window…

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
user1692333
  • 2,461
  • 5
  • 32
  • 64

2 Answers2

2

iTunes posts a distributed notification when a track change occurs. You need to register a controller to listen for those notifications:

noteCenter = NSDistributedNotificationCenter.defaultCenter()
noteCenter.addObserver_selector_name_object_(theController, 
                                             objc.selector(theController.updateTrack_,
                                                           signature="v@:@"), 
                                             "com.apple.iTunes.playerInfo", 
                                             None)

And your updateTrack_() method needs to take one argument (aside from self), which is the posted notification.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • 1
    Exactly. If you want some sample code, I wrote an iTunes monitor/controller in Python that uses this method (not designed as a general-purpose solution, just for myself) — feel free to borrow/steal anything from it: http://dev.sabi.net/trac/dev/browser/trunk/StreamVision/StreamVision.py – Nicholas Riley Nov 01 '13 at 21:34
1

You can use events with PyObjC, whether or not you can receive iTunes events depends on whether of not iTunes sends events. For all I know all iTunes status widgets just regularly poll if the iTunes track has changed.

Ronald Oussoren
  • 2,715
  • 20
  • 29