Python event handling

From MediaMonkey Wiki

Jump to: navigation, search

This is a Python script demonstrating the handling of MediaMonkey events from an external program.

It requires Python and the pywin32 package. This code was developed using Python 2.6; it should work for any Python 2.x (at least from 2.3 on), but may require changes for Python 3.

# monitor player events from MediaMonkey.  print event flag and player state info for each
# note: once started, script does not exit until MM is shut down.
import win32com.client
import pythoncom
import time
 
 
boolReps = ['F', 'T']   # hacky!
quit = False
 
class MMEventHandlers():
    def __init__(self):
        self._play_events = 0
 
    def showMM(self):
        # note: MMEventHandlers instance includes all of SDBApplication members as well
        playing = self.Player.isPlaying
        paused = self.Player.isPaused
        isong = self.Player.CurrentSongIndex
        print 'Play', boolReps[playing], '; Pause', boolReps[paused], '; iSong', isong,
        if playing:
            print '>>', self.Player.CurrentSong.Title[:40]
        else:
            print
 
    def OnShutdown(self):   #OK
        global quit
        print '>>> SHUTDOWN >>> buh-bye' 
        quit = True
    def OnPlay(self):       #OK
        self._play_events += 1
        print "PLAY #",
        self.showMM()
    def OnPause(self):      #OK
        print "PAUS #",
        self.showMM()
 
    def OnStop(self):
        print "STOP #",
        self.showMM()
    def OnTrackEnd(self):
        print "TRKE #",
        self.showMM()
    def OnPlaybackEnd(self):
        print "PLYE #",
        self.showMM()
    def OnCompletePlaybackEnd(self):
        print "LSTE #",
        self.showMM()
    def OnSeek(self):       #OK
        print "SEEK #",
        self.showMM()
    def OnNowPlayingModified(self):     #OK
        print "LIST #",
        self.showMM()
 
    # OnTrackSkipped gets an argument
    def OnTrackSkipped(self, track):  #OK (only when playing)
        print "SKIP #",
        self.showMM()
        # the type of any argument to an event is PyIDispatch
        # here, use PyIDispatch.Invoke() to query the 'Title' attribute for printing
        print '[', track.Invoke(3,0,2,True), ']'
 
 
def monitor():
    # running the script will start MM if it's not already running
    SDB = win32com.client.DispatchWithEvents('SongsDB.SDBApplication', MMEventHandlers)
 
    print "** monitor started"
    while not quit:
        # required by this script because no other message loop running
        # if the app has its message loop (i.e., has a Windows UI), then
        # the events will arrive with no additional handling
        pythoncom.PumpWaitingMessages()
        time.sleep(0.2)
 
    # note that SDB instance includes members of of the MMEventHandlers class
    print "** monitor stopped; received " + str(SDB._play_events) + " play events"
 
if __name__ == '__main__':
        monitor()
Personal tools