moonman239 moonman239 - 8 days ago 6
AppleScript Question

Why does my AppleScript program say iTunes is playing a track when iTunes isn't actually doing so?

I'm trying to make an AppleScript that tells iTunes to play a certain track. Here's my code. I'm baffled, because when I set "theCommand" to "play Shake Up Christmas by artist Train" the script works when I right-click a test e-mail and click "Apply Rules." However, it doesn't work when I tell it to play what the e-mail tells it to play.

using terms from application "Mail"
on perform mail action with messages messageList for rule aRule
tell application "Mail"
repeat with thisMessage in messageList
try
set theCommand to content of thisMessage as string
on error errMsg
display alert errMsg
end try
end repeat
end tell
tell application "iTunes"
if theCommand contains "play" then
if theCommand is equal to "play" then
play
else
set prevTIDs to text item delimiters of AppleScript
set text item delimiters of AppleScript to "play "
set subject to text items of theCommand
set text item delimiters of AppleScript to ""
set subject to "" & subject
set AppleScript's text item delimiters to " by artist "
set delimitedList to every text item of subject
set theTrack to the first item of delimitedList
try
set theArtist to the second item of delimitedList
set artistIsDefined to true
on error
set artistIsDefined to false
end try
set AppleScript's text item delimiters to prevTIDs
if artistIsDefined is true then
try
play (every track in playlist 1 whose artist is theArtist and name is theTrack)
say "Playing " & theTrack
on error errMsg
say errMsg
end try
else
play (every track in playlist 1 whose name is theTrack)
end if
end if
else if theCommand is equal to "pause" then
pause {}
else if theCommand is equal to "stop" then
stop {}
end if
end tell
end perform mail action with messages
end using terms from


The Mac will respond to an e-mail by saying "Playing (track)," but it won't play the track. The fact that the file is on a Time Capsule shouldn't matter, as iTunes can access it. (iTunes would have shown an exclamation mark to the left of the track name if it couldn't.)

Answer

My guess is that you need to change the word "every" to "first" in this command...

play (every track in playlist 1 whose artist is theArtist and name is theTrack)

I didn't test my theory, but I think by using the word "every" you get a list of tracks from that command (even if only 1 track is in the list). And iTunes doesn't know how to play a list. iTunes can play a track. So by using "first" you will get the first track found and thus it should work. Alternatively you could get the first item of the list... play (item 1 of (every track...)).