Now we have everything we need to make my program work as I wished. We start by setting some variables. You will see in the code what the variables mean.
set sleeptime to 60 * (text returned of (display dialog "For how many minutes do you wish to have media?" default answer 60)) as integer
set precision to 1
set spotifyStartTime to 3
tell application "System Events"
if (name of processes) contains "QuickTime Player" then
tell application "QuickTime Player"
repeat
delay precision
set sleeptime to sleeptime - precision
if done of front document or sleeptime is less than 1 then
quit
exit repeat
end if
end repeat
end tell
end if
end tell
As you can see, precision is how long we wait between the checks with QuickTime. Also note that we ask System Events if QuickTime is running, or it would start QuickTime to ask it if it's done.
if sleeptime is greater than spotifyStartTime then
tell application "Spotify" to activate
delay spotifyStartTime
tell application "System Events" to keystroke space
end if
Here we check if there's any time left to play music, and if there is we put Spotify on top (or start it), wait for it to logon (in case we started it) and send a space to it to make it play.
activate application "ScreenSaverEngine"
delay sleeptime - spotifyStartTime
tell application "Spotify" to quit
Now all we have to do is to start the screensaver (why not?) and wait for the time to run out. When the time is out we shut spotify down. The reason we don't just send another keystroke to it is that that keystroke would be caught by the screensaver, and the music wouldn't stop playing.