frontpage : scripts : here

Spare Parts

Use these example templates in your own scripts.

Selection Routines

Single Selected Track
Get a reference to a single selected track.
Each Selected Track
Get a list of references to each selected track.
Select Playing or Single Selected Track
Get a reference to the current track if player is paused or playing; otherwise, check for a single selected track.
Selected Tracks or Entire Playlist
Repeat with a reference to each of the selected tracks; or, if no tracks are selected, repeat with a reference for each track in the currently selected playlist.

Handlers

Is iTunes Running
Returns true or false.
Choose/Restore Encoder
Change encoders on-the-fly and restore Preferences-set encoder afterwards.
Nuke Track 1
Delete a track from iTunes entirely.
Nuke Track 2
Delete a track from iTunes entirely and delete its file immediately (and unrecoverably).
Nuke Track 3
Delete a track from iTunes entirely and move its file to the Trash.
text_to_list(), list_to_text(), replace_chars()
Frequently helpful text and list handlers.
Basic Idle Routine
Checks for new current track. Save as Stay-Open Application.
List Manually Managed iPods
Sets two corresponding lists to manually managed iPod names and source references
Export Artwork as File to Folder
Supply an iTunes track reference, path to folder as text, name of new file as text, and scale in pixels. NOTE: probably will not work with iTunes 9/Snow Leopard. See the slightly updated version below.
Export Artwork as File to Folder II
Supply an iTunes track reference, path to folder as text, name of new file as text, and scale in pixels.This version seems to work better in Snow Leopard with iTunes 9
Rating to Text Stars
Pass the value of a track’s rating property. Regretably, the chevrons in the Unicode do not translate into UPM so you’ll have to copy-and-paste this off the page.
Single Selected Track - snippet

Get a reference to a single selected track.

tell application "iTunes"
	set sel to selection
	if sel is not {} and (length of sel) is 1 then
		set aTrack to item 1 of sel
		-- do something with aTrack
		
		--
	else
		display dialog return & "Select a single track first..." buttons {"Cancel"} ¬
			default button 1 with icon 0 giving up after 15
		return
	end if
end tell


Each Selected Track - snippet

Get a list of references to each selected track.

tell application "iTunes"
	set sel to selection
	if sel is not {} then
		repeat with aTrack in sel
			-- do something with aTrack
			
			--
		end repeat
	else
		display dialog return & "No tracks are selected..." buttons {"Cancel"} ¬
			default button 1 with icon 0 giving up after 15
		return
	end if
end tell


Select Playing or Single Selected Track - snippet

Get a reference to the current track if player is paused or playing; otherwise, check for a single selected track.

tell application "iTunes"
	if player state is not stopped then
		set aTrack to current track
	else
		set sel to selection
		if sel is not {} and (length of sel) is 1 then
			set aTrack to item 1 of sel
		else
			display dialog return & "No track is playing or selected..." buttons {"Cancel"} ¬
				default button 1 with icon 0 giving up after 15
			return
		end if
	end if
	-- do something with aTrack
	
	--
end tell


Selected Tracks or Entire Playlist - snippet

Repeat with a reference to each of the selected tracks; or, if no tracks are selected, repeat with a reference for each track in the currently selected playlist.

tell application "iTunes"
	set sel to selection
	if sel is not {} then
		repeat with aTrack in sel
			-- do something with aTrack
			
			--
		end repeat
	else
		set thePlaylist to view of the front browser window
		repeat with i from 1 to (index of last track of thePlaylist)
			set aTrack to track i of thePlaylist
			-- do something with aTrack
			
			--
		end repeat
	end if
end tell


Is iTunes Running - handler

Returns true or false.

on iTunes_is_running()
	tell application "System Events"
		return (exists process "iTunes")
	end tell
end iTunes_is_running


Choose/Restore Encoder - handler

Change encoders on-the-fly and restore Preferences-set encoder afterwards.

global encoderBackup

tell application "iTunes"
	my choose_encoder()
	-- do something with new encoder
	
	--
	my restore_encoder()
end tell

to choose_encoder()
	tell application "iTunes"
		set myEncoders to name of every encoder
		set encoderBackup to name of current encoder
		set myNewEncoder to (choose from list myEncoders ¬
			with prompt "Choose an encoder..." default items ¬
			(encoderBackup as list)) as text
		if myNewEncoder is "false" then error number -128
		set current encoder to encoder myNewEncoder
	end tell
end choose_encoder

to restore_encoder()
	tell application "iTunes" to set current encoder to encoder encoderBackup
end restore_encoder


Nuke Track 1 - handler

Delete a track from iTunes entirely.

to nuke_track(aTrack)
	-- pass a track reference as aTrack
	tell application "iTunes"
		try
			delete (some track of library playlist 1 whose persistent ID is (get persistent ID of aTrack))
		end try
	end tell
end nuke_track


Nuke Track 2 - handler

Delete a track from iTunes entirely and delete its file immediately (and unrecoverably).

to nuke_track_and_delete_its_file(aTrack)
	-- pass a track reference as aTrack
	tell application "iTunes"
		try
			set loc to missing value
			if (get class of aTrack) is file track then set loc to quoted form of POSIX path of ((get location of aTrack) as text)
			delete (some track of library playlist 1 whose persistent ID is (get aTrack's persistent ID))
			if (loc is not missing value) then do shell script "rm " & loc
			return true
		on error
			return false
		end try
	end tell
end nuke_track_and_delete_its_file


Nuke Track 3 - handler

Delete a track from iTunes entirely and move its file to the Trash.

to nuke_track_and_Trash_its_file(aTrack)
	-- pass a track reference as aTrack
	tell application "iTunes"
		try
			set loc to missing value
			if (get class of aTrack) is file track then set loc to (get location of aTrack)
			delete (some track of library playlist 1 whose persistent ID is (get aTrack's persistent ID))
			if (loc is not missing value) then my trash_file(loc)
			return true
		on error
			return false
		end try
	end tell
end nuke_track_and_Trash_its_file

to trash_file(loc)
	tell application "Finder"
		try
			delete loc
		on error
			error number 1
		end try
	end tell
end trash_file


text_to_list(), list_to_text(), replace_chars() - handler

Frequently helpful text and list handlers.

on replace_chars(txt, srch, repl)
	set AppleScript's text item delimiters to the srch
	set the item_list to every text item of txt
	set AppleScript's text item delimiters to the repl
	set txt to the item_list as string
	set AppleScript's text item delimiters to ""
	return txt
end replace_chars

on text_to_list(txt, delim)
	set saveD to AppleScript's text item delimiters
	try
		set AppleScript's text item delimiters to {delim}
		set theList to every text item of txt
	on error errStr number errNum
		set AppleScript's text item delimiters to saveD
		error errStr number errNum
	end try
	set AppleScript's text item delimiters to saveD
	return (theList)
end text_to_list

on list_to_text(theList, delim)
	set saveD to AppleScript's text item delimiters
	try
		set AppleScript's text item delimiters to {delim}
		set txt to theList as text
	on error errStr number errNum
		set AppleScript's text item delimiters to saveD
		error errStr number errNum
	end try
	set AppleScript's text item delimiters to saveD
	return (txt)
end list_to_text


Basic Idle Routine - handler

Checks for new current track. Save as Stay-Open Application.

property currentDBID : missing value
property idleTime : 15

on run
	set currentDBID to missing value
	-- other initialization here...
end run

on idle
	if my iTunes_is_running() then
		tell application "iTunes"
			if player state is playing then
				set curTrack to current track
				set thisDBID to (get curTrack's database ID)
				if thisDBID is not currentDBID then
					set currentDBID to thisDBID
					-- do something with curTrack here...
					
					--
				end if
			end if
		end tell
	end if
	return idleTime
end idle

on iTunes_is_running()
	tell application "System Events"
		return (exists process "iTunes")
	end tell
end iTunes_is_running


List Manually Managed iPods - handler

Sets two corresponding lists to manually managed iPod names and source references

global this_iPod, list_of_iPod_sources, list_of_iPod_names

-- the variables will be set after handler is run:
-- list_of_iPod_sources corresponds with list_of_iPod_names

tell application "iTunes"
	my check_for_iPod()
	log list_of_iPod_sources
	log list_of_iPod_names
	-- for example:
	choose from list list_of_iPod_names
	
end tell


to check_for_iPod()
	set this_iPod to missing value
	set list_of_iPod_sources to {}
	set list_of_iPod_names to {}
	tell application "iTunes"
		set lp to every source whose kind is iPod
		if lp is {} then return
		repeat with src in lp
			my check_ipod_management(src)
		end repeat
	end tell
	
	if list_of_iPod_sources is {} then
		display dialog return & "No manually managed iPods are mounted..." buttons {"Cancel"} default button 1 with icon 0 giving up after 15 with title my_title
		error number -128
	end if
	
end check_for_iPod

to check_ipod_management(p)
	tell application "iTunes"
		try
			set x to (make new user playlist at p)
			delete x
			set end of list_of_iPod_sources to p
			set end of list_of_iPod_names to (name of p)
		end try
	end tell
end check_ipod_management


Export Artwork as File to Folder - handler

Supply an iTunes track reference, path to folder as text, name of new file as text, and scale in pixels. NOTE: probably will not work with iTunes 9/Snow Leopard. See the slightly updated version below.

tell application "iTunes"
	set sel to selection
	-- pass (iTunes track reference, path to folder as text, name of file as text, size to scale graphic to in pixels)
	my export_artwork(item 1 of sel, (path to desktop from user domain) as text, "myartworkpic", 500)
end tell

to export_artwork(theTrack, exportFolder, artworkName, target_width)
	
	tell application "iTunes"
		try
			tell theTrack to set {artworkData, imageFormat} to {(data of artwork 1), (format of artwork 1) as string}
		on error
			-- probably no artwork
			return false
		end try
	end tell
	
	set ext to ".png"
	set fileType to "PNG"
	if imageFormat contains "JPEG" then
		set ext to ".jpg"
		set fileType to "JPEG"
	end if
	
	set new_file_name to (artworkName & ext) as text
	set path_to_new_file to (exportFolder & new_file_name) as text
	
	-- if file with same name exists in same location then delete it
	-- optional
	try
		do shell script "rm " & quoted form of POSIX path of path_to_new_file
	end try
	--
	
	try
		set file_reference to (open for access path_to_new_file with write permission)
		set eof file_reference to 512
		write artworkData to file_reference starting at 513
		close access file_reference
	on error m
		try
			close access file_reference
		end try
		return false
	end try
	try
		tell application "System Events" to set file type of (path_to_new_file as alias) to fileType
	on error m
		-- may not be critical
		log ("ERROR: " & m)
	end try
	
	-- use ImageEvents to scale the photo and convert to PNG (or not)
	-- optional
	try
		tell application "Image Events"
			launch
			set this_image to open path_to_new_file
			set typ to this_image's file type
			copy dimensions of this_image to {current_width, current_height}
			if current_width is greater than current_height then
				scale this_image to size target_width
			else
				set the new_height to (current_height * target_width) / current_width
				scale this_image to size new_height
			end if
			
			-- convert to png...
			-- set new_item to ((text 1 thru -5 of ((exportFolder & new_file_name) as text)) & ".png") as text
			-- save this_image in new_item as PNG
			-- or just...
			save this_image
			
			close this_image
		end tell
		try
			-- ONLY if original was converted to PNG...
			-- do shell script "rm " & quoted form of POSIX path of path_to_new_file
		end try
		
	on error m
		log ("GENERAL ERROR: " & m)
		return false
	end try
	return true
	-- 
end export_artwork


Export Artwork as File to Folder II - handler

Supply an iTunes track reference, path to folder as text, name of new file as text, and scale in pixels.This version seems to work better in Snow Leopard with iTunes 9

tell application "iTunes"
	set sel to (first item of selection)
	# pass (iTunes track reference, path to folder as text, name of file as text, size to scale graphic to in pixels)
	my export_artwork(sel, (path to desktop from user domain) as text, "myartworkpic", 500)
end tell

to export_artwork(theTrack, exportFolder, artworkName, target_width)
	tell application "iTunes"
		try
			tell theTrack to set {artworkData, imageFormat} to {(raw data of artwork 1), (format of artwork 1) as text}
		on error
			# probably no artwork
			return false
		end try
	end tell
	
	set ext to ".png"
	set fileType to "PNG"
	if imageFormat contains "JPEG" then
		set ext to ".jpg"
		set fileType to "JPEG"
	end if
	
	set new_file_name to (artworkName & ext) as text
	set path_to_new_file to (exportFolder & new_file_name) as text
	
	# if file with same name exists in same location then delete it
	# optional
	try
		do shell script "rm " & quoted form of POSIX path of path_to_new_file
	end try
	
	try
		set file_reference to (open for access path_to_new_file with write permission)
		set eof file_reference to 0
		write artworkData to file_reference starting at 0
		close access file_reference
	on error m
		try
			close access file_reference
		end try
		return false
	end try
	
	try
		tell application "System Events" to set file type of (path_to_new_file as alias) to fileType
	on error m
		# may not be critical
		log ("ERROR: " & m)
	end try
	
	# use ImageEvents to scale the photo and convert to PNG (or not)
	# optional
	try
		tell application "Image Events"
			launch
			set this_image to (open path_to_new_file)
			copy dimensions of this_image to {current_width, current_height}
			if current_width is greater than current_height then
				scale this_image to size target_width
			else
				set the new_height to (current_height * target_width) / current_width
				scale this_image to size new_height
			end if
			
			# convert to png...
			-- set new_item to ((text 1 thru -5 of ((exportFolder & new_file_name) as text)) & ".png") as text
			-- save this_image in new_item as PNG
			# or just...
			save this_image
			
			close this_image
			quit
		end tell
		try
			# ONLY if original was converted from JPG to PNG...
			-- do shell script "rm " & quoted form of POSIX path of path_to_new_file
		end try
		
	on error m
		log ("GENERAL ERROR: " & m)
		return false
	end try
	return true
	
end export_artwork


Rating to Text Stars - handler

Pass the value of a track’s rating property. Regretably, the chevrons in the Unicode do not translate into UPM so you’ll have to copy-and-paste this off the page.

to display_track_rating_stars(r)
	-- pass a track's rating value
	set rez to ""
	repeat (r div 20) times
		set rez to (rez & («data utxt2605» as Unicode text)) as text
	end repeat
	if r mod 20 = 10 or r = 10 then
		set rez to (rez & («data utxt00BD» as Unicode text)) as text
	end if
	return rez
end display_track_rating_stars


This column is printer-friendly.
Site contents © 2001 - 2010 Doug Adams and weblished by Doug Adams, dougscripts AT mac DOT com.
All rights reserved. Legal.
AppleScript, iTunes, and iPod are registered trademarks of Apple Inc.
Image 01 Image 01 Image 01 Image 01 Image 01 Image 02 Image 03 Image 03 Image 03 Image 03