Copy iTunes selection to a new album

Alec Jacobson

December 04, 2009

weblog/

Now that nobody burns CDs for each other, lately when making mixes I go through a painful process: I set and found a few applescripts to handle automating one or two of the above tasks, but I thought I might as encapsulate the whole thing. So here's my solution as an applescript:
(*
Copy selected tracks and re-add into itunes with album = to given text and track numbers according to selection order

Author: Alec Jacobson (alecjacobsonATgmailDOTcom)
 *)
-------------------------------------

-- check if iTunes is running 
tell application "System Events"
  if (get name of every process) contains "iTunes" then set okflag to true
end tell
if okflag then
  
  tell application "iTunes"
    set mix_name to ""
    set prompt to "Mix name:"
    repeat while length of mix_name is equal to 0
      display dialog prompt default answer "My new mix" buttons {"OK", "Cancel"} default button 1
      copy the result as list to {text_returned, button_pressed}
      set mix_name to text_returned
      set prompt to "Mix name (must enter something):"
    end repeat
    
    set selected_tracks to selection
    if selected_tracks is {} then -- no selection
      display dialog "Select some tracks first..." buttons {"OK"} default button 1
    else
      set selected_songs to ""
      set track_number to 1
      set number_of_tracks to length of selected_tracks
      repeat with this_track in selected_tracks
        do shell script "cp " & (quoted form of POSIX path of (get this_track's location)) & " " & (quoted form of (POSIX path of (get this_track's location) & ".tmp.mp3"))
        set new_copy to add (POSIX file (POSIX path of (get this_track's location) & ".tmp.mp3")) as alias to source "Library"
        
        
        set errNum to -54 -- expect a file permission error (itunes takes a second...)
        repeat while (errNum is equal to -54)
          try
            set album of new_copy to mix_name
            set track number of new_copy to track_number
            set track count of new_copy to number_of_tracks
            set compilation of new_copy to true
            
            set track_number_string to track_number as string
            if (track_number < 10) then
              set track_number_string to "0" & track_number_string
            end if
            
            set new_path to location of new_copy
            tell application "Finder" to set name of new_path to "" & track_number_string & " " & (name of new_copy) & ".mp3"
            
            set errNum to 0
          on error errText number errNum
            if errNum is not equal to -54 then
              error errText number errNum
            end if
            delay 1.0E-4
          end try
        end repeat
        
        set track_number to track_number + 1
      end repeat
    end if
  end tell
end if