Welcome, guest | Sign In | My Account | Store | Cart

This is a simple console application that you can use to schedule iTunes to begin playing a playlist at a certain time. The volume ramps up to full level over about 1 minute so you aren't blasted awake.

I haven't worked with Python much so any suggestions, comments are appreciated.

Thanks, Josh

Python, 170 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
## Wakeup_With_iTunes.py
## Author:   Joshua Bloom
## Date:     29 January 2006
## Version:  1.0
## Location: http://jbloomdesign.com/blog/2006/01/28/wake-up-with-itunes/
## Copyright (c) 2006, Joshua Bloom
## With thanks to James Thiele http://www.eskimo.com/~jet/python/examples/cmd/ for the console code
import cmd
import os
import pythoncom
import subprocess
import sys
import time
import thread
import win32com.client

class Console(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.playSongBool = False
        self.completekey = None
        self.prompt = "=>> "
        self.intro  = "Welcome to the Itunes wake up console! \n\twake morning_playlist 7:00\nStarts your morning_playlist at 7:00AM\nType help for more command information."

    def do_wake(self,args):
        """Wake starts a song for you. Format is wake playlistname time(24hr) IE wake morningSongs 7:00
        """
        try:
            list = args.split()
            self.playlist = list[0]
            timeVal = list[1]
            splitTime = timeVal.split(":")
            self.hour = splitTime[0]
            self.minute = splitTime[1]
            self.playSongBool = True
            #Check for the named Playlist
            if (self.playListExists(self.playlist)):
                thread.start_new_thread(self.timeChecker,())
            else:
                print ("The playlist %s doesn't exist, your should try one that does" % self.playlist)
        except:
            print"Please format your request correctly: wake playlist time(24hr)"

    def do_cancelwake(self,args):
        """Cancelwake cancels your requested wakeup
        """
        if (self.playSongBool):
            self.playSongBool = False
            self.hour = None
            self.minute = None
            self.song = None
            print("Your wakeup song has been cancelled")
        else:
            print("Nothing currently scheduled so I can't cancel anything.")

    def do_showwake(self,args):
        """Show the Current playlist and Time
        """
        if (self.playSongBool):
            print("Playlist: %s will play at Time: %s:%s" % (self.playlist, self.hour, self.minute))
        else:
            print("Nothing currently scheduled")

    def timeChecker(self):
        while (1):
            if (self.playSongBool and
                int(time.localtime().tm_hour) == int(self.hour) and
                int(time.localtime().tm_min) == int( self.minute) ):
                self.playSong()
            time.sleep(5)

    def playListExists(self, playlistName):
        iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application")
        playlists = iTunes.LibrarySource.Playlists
        numPlaylists = playlists.Count
        while (numPlaylists != 0):
            currPlaylist = playlists.Item(numPlaylists);
            if (currPlaylist.Name == playlistName):
                return True
            numPlaylists -= 1
        return False

    def playSong(self):
        print("Here's your scheduled wakeup! %s " % time.asctime())
        pythoncom.CoInitialize ()
        self.playSongBool = False
        iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application")
        playlists = iTunes.LibrarySource.Playlists
        numPlaylists = playlists.Count
        while (numPlaylists != 0):
            currPlaylist = playlists.Item(numPlaylists);
            if (currPlaylist.Name == self.playlist):
                try:
                    vol = 0
                    iTunes.SoundVolume = vol
                    currPlaylist.PlayFirstTrack()
                    #Ramp Up Volume
                    while (vol < 100):
                        time.sleep(.5)
                        iTunes.SoundVolume = vol
                        vol += 1
                    break
                except:
                    pass
            numPlaylists -= 1

    ## Command definitions ##
    def do_hist(self, args):
        """Print a list of commands that have been entered"""
        print self._hist

    def do_exit(self, args):
        """Exits from the console"""
        return -1

    def do_help(self, args):
        """Get help on commands
           'help' or '?' with no arguments prints a list of commands for which help is available
           'help <command>' or '? <command>' gives help on <command>
        """
        ## The only reason to define this method is for the help text in the doc string
        cmd.Cmd.do_help(self, args)

    ## Override methods in Cmd object ##
    def preloop(self):
        """Initialization before prompting user for commands.
           Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub.
        """
        cmd.Cmd.preloop (self)   ## sets up command completion
        self._hist    = []      ## No history yet
        self._locals  = {}      ## Initialize execution namespace for user
        self._globals = {}

    def postloop(self):
        """Take care of any unfinished business.
           Despite the claims in the Cmd documentaion, Cmd.postloop() is not a stub.
        """
        cmd.Cmd.postloop(self)   ## Clean up command completion
        print "Exiting..."

    def precmd(self, line):
        """ This method is called after the line has been input but before
            it has been interpreted. If you want to modifdy the input line
            before execution (for example, variable substitution) do it here.
        """
        self._hist += [ line.strip() ]
        return line

    def postcmd(self, stop, line):
        """If you want to stop the console, return something that evaluates to true.
           If you want to do some post command processing, do it here.
        """
        return stop

    def emptyline(self):    
        """Do nothing on empty input line"""
        pass

    def default(self, line):       
        """Called on an input line when the command prefix is not recognized.
           In that case we execute the line as Python code.
        """
        try:
            exec(line) in self._locals, self._globals
        except Exception, e:
            print e.__class__, ":", e

if __name__ == '__main__':
        console = Console()
        console . cmdloop() 

Notes: * Your playlist name can’t have any spaces in it. * Time is entered in 24hr format I.E. 6:30PM would be entered as 18:30 * For now this is Windows only as it relies on COM scripting.

The console code comes from James Thiele http://www.eskimo.com/~jet/python/examples/cmd/