A Track "Selection" Trick I Learned

last updated apr 16 '02

I try to set up most of my scripts that operate on tracks to detect selected tracks or the entire playlist of tracks. The script will figure out if a selection of tracks is made and copy those tracks to a list variable; or if no selection is made then all the tracks in the playlist are copied to the list variable.

The way I have been doing this is:

tell application "iTunes"
	set fx to fixed indexing
	set fixed indexing to true
	set thisPlaylist to view of front window
	if selection is {} then
		set Tracks_To_Use to every track of thisPlaylist
	else
		set Tracks_To_Use to selection
	end if
	
	-- now do something with the Tracks_To_Use list... 
	
	set fixed indexing to fx
end tell

(Setting fixed indexing to true prohibts the playlist from resorting if track info changes during the scripting operation—a potentially dangerous situation. When finished, restore the fixed indexing variable.)

Generally this script works great. Until you encounter an extraordinarily long selection or Playlist. I'm talking thousands of tracks! There is a limit to the number of items in a list that AppleScript can deal with and if you go over that limit you can generate an error, crash iTunes, and never get a thing done.

To avoid the error, I avoid creating a list in AppleScript to begin with and instead use a reference to the selection object in iTunes, rather than copying its contents to a variable. Or, if the case is that the entire playlist is needed, use a reference to it. I do this by establishing a flag called "using_selection". Later, this variable will determine which iTunes object—selection or selected Playlist—to get tracks from:

tell application "iTunes"
	set fx to fixed indexing
	set fixed indexing to true
	set thisPlaylist to (a reference to (get view of front window))
	if selection is not {} then -- test if there is a selection...
		set using_selection to true
		set idx to (count selection's items)
	else -- its the whole playlist
		set selectedTracks to (get a reference to thisPlaylist)
		set using_selection to false
		set idx to (count thisPlaylist's tracks)
	end if
	
	-- later...
	
	repeat with j from 1 to idx
		if using_selection then
			set thisTrack to item j of selection
		else
			set thisTrack to track j of selectedTracks
		end if
		
		-- thisTrack now set, do some stuff to it
		
	end repeat
	set fixed indexing to fx
end tell

Using this strategy, I have encountered no difficulties in selecting an unlimited number of tracks, or accessing every track in a very lengthy playlist.

BTW: Another benefit is a tremendously tangible boost in speed, since AppleScript does not have to course through an internal list during the repeat loop.

Site contents © 2001 - 2012 Doug Adams and weblished by Doug Adams, dougscripts AT mac DOT com.
All rights reserved. Legal.
AppleScript, iTunes, iPod, iPad, and iPhone are registered trademarks of Apple Inc.