title: Detect the end of a Spotify track with Applescript?
body: <p>I'm writing an Applescript that displays a notification with the name, album, and artist of the current  Spotify track. Yes, I'm aware there is already an app that does this, but even with the latest version, it's very buggy and behaves erratically. </p>
  
  <p>So far, I have a good little script. Here it is:</p>
  
  <pre><code>repeat until application "Spotify" is not running
      tell application "Spotify"
          set theSong to name of current track
          set theAlbum to album of current track
          set theArtist to artist of current track
          set theTime to player position
          set theDuration to duration of current track
      end tell
  
  
      (* This sets the amount of delay to the length of the song minus the current place in the song, which leaves us with the amount of time left until the next song plays.*)
      set delayTime to theDuration - theTime + 0.5
  
      tell application "Spotify"
          if player state is playing then
              display notification theArtist with title theSong subtitle theAlbum
          end if
  
          delay delayTime
  
      end tell
  end repeat
  </code></pre>
  
  <p>Basically, the problem with this is if I pause or change the track, delay stays the same and thus doesn't display the notification when the song starts. </p>
  
  <p>I used delay in this script because I don't really know a better way of checking for the end of a track. Is there any Applescript event for the end of a song (or the beginning of a new one?)</p>
  
  <p>Thanks.</p>
  
  <p>P.S., If this question is too complicated, feel free to ask more.</p>