0

I have an AppleScript script for Music that processes the selected tracks and modifies the track name.

Basically, it works.

If I select one item, it works without fail.

If I select multiple items, it will correctly modify the first item. Sometimes it will stop there; other times, it will process several more items. Rarely, it will process the entire list of selected tracks.

I've put in a delay to see if that would help, but it doesn't.

Any idea why this might be happening?

Here's my code:

tell application "Music"
    set selectedTracks to selection
    if selectedTracks is {} then return
    if (get class of (item 1 of selectedTracks)) is not file track then return
    
    repeat with i from 1 to (length of selectedTracks)
        set thisTrack to item i of selectedTracks
        tell thisTrack to set {trackName} to {get name}
        
        set my text item delimiters to {"/"}
        set theResults to text items in trackName
        set newTrackName to item 2 of theResults
        set newArtist to item 1 of theResults
        
        set newTrackName to my removeLeadingAndTrailingSpacesFrom(newTrackName)
        set newArtist to my removeLeadingAndTrailingSpacesFrom(newArtist)
        
        set name of thisTrack to newTrackName
        set artist of thisTrack to newArtist
        
        delay 1
        
    end repeat
end tell

on removeLeadingAndTrailingSpacesFrom(sourceString)
    repeat while character 1 of sourceString = " "
        set sourceString to text 2 thru end of sourceString
    end repeat
    repeat while last character of sourceString = " "
        set endIndex to (length of sourceString) - 1
        set sourceString to text 1 thru endIndex of sourceString
    end repeat
    return sourceString
end removeLeadingAndTrailingSpacesFrom
0

I can't test this properly without messing up my own music library, but I suspect the problem is with this line:

set selectedTracks to selection

If Music is being true to form, this would pass back the current selection as a reference to a list of tracks. Passing by reference means that the list is stored in Music.app and the script retrieves items as needed; it also means that if the selection changes during script execution (which it probably does, since you're changing track names) it will throw off the indexes and references within the script. This might cause errors, or may just trick the repeat loop into think it has worked through all the items, when in fact they've merely disappeared from view.

The solution would be to dereference:

set selectedTracks to (get selection)

This should convince Music.app to pass an explicit list at the beginning of the script, so that changes in the selection would not propagate back to the script.

| improve this answer | |
  • Interesting. I'll try it and report back. Thanks. – Zonker.in.Geneva Jul 29 at 21:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .