Given an album ID (e.g. 1646945378) and a track ID (e.g. 1646945384), is there a way to add a track to the library using AppleScript/JXA?
- macOS: Sonoma 14.2
- Music: 1.4.2.83
I know you can do something like
duplicate current track to playlist "Library"
Ideally, I don’t want to play the track before adding it to my library, but I can’t find a way to get a shared track
object from just the album and track IDs.
I have figured out how to open the album and select the track:
set albumID to "1646945378"
set trackID to "1646945384"
tell application "Music" to open location "itmss://geo.music.apple.com/album/" & albumID & "?i=" & trackID & "&ls=1&app=music"
However, I can’t get the selected track. This code logs empty lists:
tell application "Music"
log (get browser window 1's selection)
log (get selection)
-- Because an album, not a playlist, is being browsed, ‘get browser 1's view’ doesn’t work either
end tell
As a last resort, I thought I could try manually clicking the add to library button, but I can’t figure out how to tell if a track is selected or not as all of the UI elements seem to have selected:missing value
.
tell application "System Events"
tell process "Music"
set tracksList to get window 1's splitter group 1's scroll area 2's list 1's list 2
set trackGroups to tracksList's groups
-- With the example track above, the first track is selected
set t1 to get trackGroups's item 1
set t2 to get trackGroups's item 2
-- Each group has one child UI element: another group. This group contains stuff like
-- the track number, name, buttons, etc.
log (get t1's properties) -- focused:missing value, selected:missing value
log (get t2's properties) -- focused:missing value, selected:missing value
log (get t1's group 1's properties) -- focused:false, selected:missing value
log (get t2's group 1's properties) -- focused:false, selected:missing value
end tell
end tell
I could use the Apple Music API to get the track number of the track I want to add to my library (or in my specific use-case I wouldn’t even need to use the API to do this) and click the add to library button that way.
However, this all seems quite tedious and annoying for something that I believe should be a builtin AppleScript command. Is there a better/easier way of doing this?
Related: