applescriptosascriptapple-music

How to fix "original file could not be found" error via apple script


I have an issue with my music library. Some songs I am unable to play because they cannot be found locally. Here's an example of the error messages I get when playing a specific song:

The song ... could not be used because the original file could not be found. Would you like to locate it?

enter image description here

I can simply press Cancel and the song will be matched via the Apple Music Service. This allows me to then play the song.

This issue has been discussed here, albeit not in an automated way. Hence, I would like to find an automated solution.

For this, I took the approach of looping through my library by playing each song. By default, if a song cannot be found, the script automatically skips to the next song. However, I would like the script to deal with the "file not found" errors and press Cancel.

My current attempt unfortunately does not work:

-- Play first song in library (turn off shuffle and repeat)
set i to 4000 --number of songs in library
repeat while i > 0
    tell application "Music" to play (next track)
    tell application "System Events"
        key code 53
    end tell
    set i to i - 1
end repeat

How can I force the script to deal with these pop-up errors?

Note: I am also open to any other, more efficient solution to my problem if you have any suggestions. I decided not to go for the Locate option because it takes more time and I will delete any unreferenced songs from my disk at a later stage anyways.


Solution

  • UPDATED VERSION. Following script doesn't play tracks and programatically clicks button "Cancel" when track is corrupted. Like described by OP fixing tracks manually workflow:

    tell application "Music"
        activate -- required
        tell source "Library"
            repeat with nextTrack in tracks
                try
                    with timeout of 2 seconds
                        set theResult to play (contents of nextTrack)
                    end timeout
                    theResult
                on error
                    delay 1
                    tell application "System Events" to tell process "Music" to tell window 1 to if UI element "Cancel" exists then click UI element "Cancel"
                end try
                stop
            end repeat
        end tell
    end tell