user1692333
user1692333

Reputation: 2597

Is it possible to use iTunes events in Python via PyObjC?

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…

Upvotes: 0

Views: 262

Answers (2)

jscs
jscs

Reputation: 64002

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.

Upvotes: 2

Ronald Oussoren
Ronald Oussoren

Reputation: 2810

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.

Upvotes: 1

Related Questions