Importing file(s) to Music

There is something I don’t understand re importing files to music w AppleScript:

tell application "Music"
	set toPlaylist to "NewTracks"	
	set newFile to (choose file with prompt "Select track you want to add...")
add newFile to playlist toPlaylist
end tell

The above works to to import one file into the playlist.

Then why doesn’t the following work to import all the files in a chosen folder the same way?

set toPlaylist to "NewTracks"

tell application "Music"
	set file_list to every file of (choose folder with prompt "Select Folder to Import to Music")
	if not (user playlist toPlaylist exists) then
		make new user playlist with properties {name:toPlaylist}
	end if
	repeat with newFile in file_list
		add newFile to playlist toPlaylist
	end repeat
end tell

What does “doesn’t work” mean?

Two things.

  1. if the playlist already exist you might want to remove all of its tracks
    It might not add them if they already exists.

  2. log the file and log it’s class in each script.
    You may need to get its posixPath or alias.

From another script I’ve found this:

set these_items to list folder this_folder without invisibles
	repeat with i from 1 to the count of these_items
		set this_item to alias ((this_folder as text) & ":" & (item i of these_items))

So you may not be getting a full path when you get the folder items, but a reference of that file only. Which is why the above script creates a full path to each file

1st Script Add This:

log {"newFile is:", newFile}
	log {"newFile Class is:", class of newFile}


choose file with prompt “Select track you want to add…”
(newFile is:, alias Kaptin:Users:kerry:Music:NML Tests:911 Is a Joke.mp3)
(newFile Class is:, alias)

Running Folder Script get this error:

iTunes got an error: Can’t get every file of alias “Kaptin:Users:kerry:Music:NML Tests:”.

Then I changed it to this:

set file_list to list folder of (choose folder with prompt "Select Folder to Import to Music") without invisibles

and again it errors. Here’s the output of the same logging:

choose folder with prompt “Select Folder to Import to Music”
list folder alias “Kaptin:Users:kerry:Music:NML Tests:” without invisibles
list folder alias “Kaptin:Users:kerry:Music:NML Tests:” without invisibles

exists user playlist “NewTracks”
(newFile is:, 911 Is a Joke.mp3)
(newFile Class is:, text)
add “911 Is a Joke.mp3” to playlist “NewTracks” ******* THIS ERRORS OUT

So yeah as it the other script you need to rebuild the complete file path.


  1. Choose folder command should be out of tell application “Music” block, because it is command of Standard Additions.

  2. The files of folder doesn’t exist for the until you add them to it. So, you should ask for the files of the folder the System Events, Finder, or the NSFileManager (AsObjC).

  3. You can get directly the list of HFS paths instead of the files, to work with them later, inside the tell application "Music" block.

  4. We should filter invisible files, like .DStore

  5. we should avoid adding duplicates to the playlist

set toPlaylist to "NewTracks"

-- choose folder command out of tell application "Music" block
set aFolderHFS to (choose folder with prompt "Select Folder to Import to Music") as text

-- Get hfs paths list, using "System Events"
tell application "System Events" to ¬
	tell (files of folder aFolderHFS whose type identifier is "") to ¬
		set hfsPaths to path

tell application "Music"
	-- Create new playlist if it doesn't exist already
	if not (user playlist toPlaylist exists) then make new user playlist with properties {name:toPlaylist}
	-- Get names of songs, which is already in the playlist
		set trackNames to name of tracks of playlist toPlaylist
	on error
		set trackNames to {}
	end try
	-- Add files one by one, deleting duplicates
	repeat with i from 1 to count hfsPaths
		set newTrack to add file (get item i of hfsPaths) to playlist toPlaylist
		if (name of newTrack) is in trackNames then delete newTrack
	end repeat
	return tracks of playlist toPlaylist
end tell

NOTE: maybe, exists better way to avoid adding duplicate songs than 1) adding song, 2) getting its name from the app, 3) deleting if it is duplicate.

Yeah unfortunately that’s a problem with adding tracks via AppleSceipt
If you import via the Apps menu and the file is already in your library, then
It won’t add it.

When you add via AppleScript it will add duplicates.
It appends a number to the file name.

In general, it is strange that lacks an import command with checking for duplicates, similar to the one that has. This is an obvious flaw, which I hope will be fixed in future versions of

Like I said it may do it if you import it from the Music app.
But not via scripting.

The issue with Songs / Files / Tracks is that there’s no way to quickly identify a duplicate.
Also it will depend on you import settings preferences. There are two options that complicate things.

  1. Copy Files to Music Library
  2. Keep Music Files Organized

When you import a song in the iTunes / Music and copy Files is Set:

  1. It will copy that file to your Music Folder/iTunes/iTunes Media/Music folder
  2. It will process the file and pull out any meta data that is embedded in the file
  3. if you have Keep Music Files Organized then it will apply changes to the file name and
    change it to the Name of the Song and Organize it into a Folders based on the Artist / Album Artist and Album Name

So problems with this are if your importing file has different meta data, even if one character
is different it will after the file name and where it gets placed

I think the only way it won’t add a new file is if the file your trying to add is already in it’s Library database library file / XML file

It is possible to try to do this in your script. But you would have to :

  1. Extract the AVMeta data from the file using AVURLasset.
  2. Be able to load the iTunes / Music XML file (or using ITLibrary Framework)
  3. Do a bunch of filtering with NSPredicate’s , compare methods to search the loaded library for
    matching tracks.
  4. If found don’t add the track.
  5. But again there are some many other variables that could come into place even if it finds a matching already loaded track.
  • if you filters and found same Track Name, Artist, Album
  • your new tracks might be different length, different bitRate, different format, etc.
  • your new tracks might be remastered and sound better etc.

Yes this all sucks big time. I’m a DJ and a programmer and I’ve been trying to come up
with many methods to Prevent this at the start. But more so the solutions arise from having
to do the DeDuplication after the fact.

  • you may want to add a better / higher quality file thats a duplicate
  • you may want to REPLACE all your old duplicate
  • but what you want is the NEW MASTER to replace all the old dupe tracks in all of
    the playlists that they were in.
  • you may want to transfer over ratings and other meta data from the old files
  • many DJ software have CUEs, bpm and other custom data stored in the files and also
    their own playlists as well.

All of this is very complicated. I’ve got the iTunes side worked out but still working on
a workflow for Traktor my DJ software.

here’s an article that cover a lot, the site is amazing for scripts and scripting info :

The best tool I’ve found for iTunes is one of dougs:

So I’m currently recreating DougScript’s “Drop Folders to Make Playlists” script.
Adapting it so that it will also in iTunes create parent folders and move playlists and sub playlist folders to their parent folder… based on what is in the finder.
Doug’s script has an option to name playlist based on their parent folder by Prefixing the parent folder name. I’m adapting mine so if the parent folder has the suffix “PREFIX” then it will prefix that to the playlist name, and also create and move the playlists to that folder in iTunes.
I will share the full script when i’m done.

As I’ve been working on it, like you, I suffer the frustration of possibly adding another duplicate file to iTunes, I’ve figure out how to approach this. In my script I want to present an alert to the user about possibly importing a duplicate and choose to:

  1. not import the file
  2. not import and use a selected duplicate in the playlist instead
  3. import both the new file and also add the selected duplicates to the playlist
  4. also add the option to add to the Comments TAG “DUPE”

So the main thing that is needed to check for dupes is TAG info from the files.
You can’t get this from iTunes because it hasn’t import the file yet. So I discovered that
Shane’s BridgePlus has the method


use scripting additions
use framework "Foundation"
use script "BridgePlus"
load framework

set theResult to current application's SMSForder's spotlightDataFor:aFile

here is theResult on a m4a audio file

aRecord is:, (NSDictionary) {kMDItemMediaTypes:{"Sound"}, kMDItemAudioSampleRate:44100, kMDItemFSContentChangeDate:(NSDate) "2021-11-05 08:28:46 +0000", kMDItemAudioChannelCount:2, kMDItemTotalBitRate:511999, kMDItemAudioBitRate:511999, kMDItemFSTypeCode:0, kMDItemDisplayName:"Walk The Walk", kMDItemFSLabel:0, kMDItemFSIsExtensionHidden:NO, kMDItemAuthors:{"Gaz Coombes"}, kMDItemContentCreationDate:(NSDate) "2021-11-05 08:28:36 +0000", kMDItemContentTypeTree:{"", "public.mpeg-4-audio", "", "public.audiovisual-content", "", "public.item", "public.content"}, kMDItemAudioEncodingApplication:"fdkaac 0.6.3, libfdk-aac 4.0.0, CBR 512kbps", kMDItemFSFinderFlags:0, kMDItemAlternateNames:{"/Volumes/Panko/Music to Install/Soulseek Downloads/Complete Converted/m4a/2021 11 New Music/2021 1103 All/2021 1022 Rediscover/Gaz Coombes - 03 - Walk The Walk.m4a"}, kMDItemDurationSeconds:236.213333333333, kMDItemFSSize:15469911, kMDItemFSName:"Gaz Coombes - 03 - Walk The Walk.m4a", kMDItemAudioTrackNumber:3, kMDItemRecordingYear:2018, kMDItemDateAdded:(NSDate) "2021-11-05 08:28:36 +0000", kMDItemFSCreationDate:(NSDate) "2021-11-05 08:28:36 +0000", kMDItemPhysicalSize:15470592, kMDItemFSCreatorCode:0, kMDItemFSInvisible:NO, kMDItemKind:"Apple MPEG-4 audio", kMDItemFSOwnerUserID:89, kMDItemContentModificationDate:(NSDate) "2021-11-05 08:28:46 +0000", kMDItemTitle:"Walk The Walk", kMDItemAlbum:"World's Strongest Man", kMDItemContentType:"", kMDItemLogicalSize:15469911, kMDItemFSOwnerGroupID:89}

The main keys main be interested in are:
(note: authors returns a list/array so you have to as for firstObject()


once you have that basic info from the file.
You can then search iTunes for matching dupe files.
And go from there

Note you can also use my Metadata Lib, if you want someting a little more lightweight:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
use script "Metadata Lib" version "2.0.2"

set theMeta to fetch metadata for item someFile return style metadata record

Available from: