Search code examples
macosapplescriptitunes

Get path to main iTunes library and play a song from it


I currently have an Applescript that lets you type in a song and play it.

Here it is:

    set userInput to text returned of (display dialog "Type something" default answer "")
if userInput contains "Play " then
    set {TID, text item delimiters} to {text item delimiters, {"Play "}}
    if length of userInput is greater than or equal to 2 then set resultString to text item 2 of userInput
    set text item delimiters to TID
    set playSong to (resultString as string)
    tell application "iTunes"
        set mySongs to every track of library playlist 1 whose name is playSong
        repeat with aSong in mySongs
        play aSong
        end repeat

        if (count of mySongs) = 0 then
            say "Song not found"
        end if
    end tell
end if

Basically, I need to get the path to the main iTunes library and play a song from it. Currently, to search for songs, iTunes has to open. And if it can't find the song, it just stays open. I want to search the actual iTunes directory to make it so if iTunes cannot find a song, it doesn't open

I have no idea how to do this.

Thanks


Solution

  • Here is the script to search in the "iTunes Library.xml" file.

    set XMLFile to my get_iTunes_Library_xml()
    set userInput to text returned of (display dialog "Type something" default answer "Play ")
    if userInput begins with "Play " and length of userInput > 5 then
        set playSong to text 6 thru -1 of userInput
        set searchString to "<key>Name<\\/key><string>" & playSong & "<\\/string>" --  to match exact name 
        if (my searchTrackName(searchString, XMLFile)) is not "" then
            tell application "iTunes" to play (tracks whose name is playSong)
        else
            say "Song not found"
        end if
    end if
    
    on searchTrackName(t, f) -- search in iTunes Library.xml file
        if "&" is in t then set t to do shell script "sed  \"s/&/&#38;/g\" <<<" & quoted form of t -- to replace "&" by "&#38;"
        try -- return a count of matching lines
            return do shell script "grep -c -m1 -i " & (quoted form of t) & " " & f -- "-i" equal case insensitive, "-m 1" to exit at first match
        end try
        return ""
    end searchTrackName
    
    on get_iTunes_Library_xml() -- get the path
        do shell script "defaults read com.apple.iApps iTunesRecentDatabases | sed -En 's:^ *\"(.*)\"$:\\1:p' |/usr/bin/perl -MURI -e 'print URI->new(<>)->file;'"
        return quoted form of the result
    end get_iTunes_Library_xml
    

    The "com.apple.iApps.plist" file contains the path to yours iTunes libraries (if you have more than one), the script get the path of the "iTunes Library.xml" file of the current library.