DIY Dayparting

Hi.

I haven’t been following this thread and haven’t tried your script. But looking through it quickly:

The descriptor problem is because you’ve changed the value of playlistMerged from the playlist’s name to the playlist itself, so putting ‘playlist’ in front of it again is wrong. Either keep the name and put ‘playlist’ in front of it or use the playlist and leave out the word ‘playlist’ in subsequent references to it:

-- set playlistMerged to user playlist playlistMerged -- leave this out
repeat
	set tr to get tracks of playlist playlistMerged -- 'playlist' + the name in the variable

. or .

set playlistMerged to user playlist playlistMerged -- set the variable to the playlist object
repeat
	set tr to get tracks of playlistMerged -- the playlist object in the variable

The other problem you mentioned:

The variable playlistUpNext needs to be declared global at the top of the script so that it can be seen in both the run and idle handlers.

good heavens, thank you NG!

The descriptor problem is because you’ve changed the value of playlistMerged from the playlist’s name to the playlist itself” seems stupidly obvious in retrospect, guess i was just staring too long, thank you.

Ӯ

i cannot get past the mysterious “parameter error.”

In fact, under analysis, i cannot get iTunes to play anything via AppleScript.

I tried several different ways to get any playlist at all playing; no results.

Eventually, i just tried to get anything to play…

tell application "iTunes"
	activate
	play
end tell

Nothing. iTunes just sits there.

I engaged in a little code cleanup, basically fiddling while Rome burns.

Here is the latest version of the script, which does everything except actually play

set PlaylistTVShow to ({first item of my text_to_list((do shell script "/usr/local/bin/icalbuddy -eed -nc -b \"\" eventsNow"), return)} as text) --Get Current Calendar Event via iCalBuddy hasseg.org/icalBuddy

global playlistUpNext
set playlistUpNext to "[some filler playlist TBD]"

tell application "iTunes"
	--Shuffle based on "CK's Evenly-shuffled Playlists v0.6" by Charles Kelly http://www.manythings.org/mac/
	set playlistMerged to "Now Playing"
	set PlaylistInterstitials to "[ID-D]" -- Intersitials for the [D]aytime broadcast
	
	if (not (exists playlist playlistMerged)) then
		set playlistMerged to make new user playlist with properties {name:playlistMerged} -- if no playlist, make it
	else
		set playlistMerged to user playlist playlistMerged -- if playlist, clean it out
		delete tracks of playlistMerged
	end if
	
	set x to count of tracks of playlist PlaylistTVShow -- length based on requested TV Show
	set MergedTracks to {}
	repeat with i from 1 to x
		set theTrack to some track of playlist PlaylistInterstitials
		set enabled of (duplicate theTrack to playlistMerged) to true
		set MergedTracks to MergedTracks & (database ID of theTrack)
		set theTrack to track i of playlist PlaylistTVShow
		set enabled of (duplicate theTrack to playlistMerged) to true
		set MergedTracks to MergedTracks & (database ID of theTrack)
	end repeat
	
	play playlistMerged
	
end tell

on idle --wait for playlist to finish
	tell application "iTunes"
		try
			if player state is not stopped then return 5
		on error
			return 5
		end try
		play playlist playlistUpNext
	end tell
	return 5
end idle

on text_to_list(txt, delim)
	set saveD to text item delimiters
	try
		set text item delimiters to {delim}
		set theList to every text item of txt
	on error
		set text item delimiters to saveD
	end try
	set text item delimiters to saveD
	return (theList)
end text_to_list

under further analysis, basically NOTHING I DO will get iTunes to play.

press space bar in active window, click the play triangle, select “Play” from the Controls menu, NOTHING.

Double-clicking will result in the selected item playing once then returning to the playlist window”iTunes will NOT play any playlist in sequence.

this is weird and infuriating.

I’m going to get coffee.

Ӯ

PS. another script attempt; failed, but just checking all variables

tell application "iTunes"
	activate
	set view of browser window 1 to playlist "Now Playing"
	tell application "System Events" to keystroke "a" using command down
	play playlist "Now Playing"
end tell

Hello

I renamed several variables to make your script more understandable.

When it IS a string (the name of a playlist) I use : somethingName
When it IS a list (a playlist) I use : somethingList
With these changes, I’m quite sure that you will understand better what is at work.

global playlistUpNextName

--Get Current Calendar Event via iCalBuddy hasseg.org/icalBuddy
set PlaylistTVShowName to first item of my text_to_list((do shell script "/usr/local/bin/icalbuddy -eed -nc -b \"\" eventsNow"), return) as text # Here, it is a string, no need to coerce it later

# Moved here and renamed to make clear that they are names (string) not playlist (list)
# As they are strings they aren't iTunes objects

set playlistMergedName to "Now Playing"
set PlaylistInterstitialsName to "[ID-D]" -- Intersitials for the [D]aytime broadcast.
set playlistUpNextName to "[some filler playlist TBD]"

tell application "iTunes"
	--Shuffle based on "CK's Evenly-shuffled Playlists v0.6" by Charles Kelly http://www.manythings.org/mac/
	if (playlist playlistMergedName) is {} then
		set playlistMergedList to make new user playlist with properties {name:playlistMergedName} -- if no playlist, make it
	else
		set playlistMergedList to user playlist playlistMergedName -- if playlist, clean it out
		--repeat # My understanding is that this instruction (and its end one) is useless
		set tr to get tracks of playlistMergedList
		--if tr is {} then exit repeat # Thanks to Nigel who pointed that it must be disabled!
		repeat with t in tr
			delete t
		end repeat
		--end repeat
	end if
	
	set x to count tracks of playlist PlaylistTVShowName -- length based on requested TV Show
	set MergedTracks to {}
	repeat with i from 1 to x
		set theTrack to some track of playlist PlaylistInterstitialsName
		set theTrackID to database ID of theTrack
		set enabled of (duplicate theTrack to playlistMergedList) to true
		set end of MergedTracks to theTrackID # do the same thing but I think that it's more clear
		set theTrack to track i of playlist PlaylistTVShowName
		set theTrackID to database ID of theTrack
		set enabled of (duplicate theTrack to playlistMergedList) to true
		set end of MergedTracks to theTrackID # do the same thing but I think that it's more clear
	end repeat
	
	--play playlist "Now Playing" -- use of playlistMerged gets "descriptor type mismatch" / current syntax results in "iTunes got an error: Parameter error." I DON'T KNOW WHAT TO BELIEVE ANYMORE.
	play playlist playlistMergedName
	set full screen to true
	
end tell

--wait for playlist to finish

on idle
	tell application "iTunes"
		try
			if player state is not stopped then return 5
		on error
			return 5
		end try
		play playlist playlistUpNextName # defined as a global value
	end tell
	return 5
end idle

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
		set AppleScript's text item delimiters to saveD
	on error errStr number errNum
		set AppleScript's text item delimiters to saveD
		error errStr number errNum
	end try
	return theList
end text_to_list

Yvan KOENIG running Sierra 10.12.1 in French (VALLAURIS, France) samedi 10 décembre 2016 17:23:32

According to iTunes’s scripting dictionary, ‘play’ plays tracks or files. There’s no mention of it playing playlists. Maybe you have to repeat through the tracks in a playlist and play them individually.

Hello Nigel

A I was not accustomed to scripting iTunes I ran a short test script before posting.

tell application "iTunes"
	set theNames to name of playlists
	play playlist (item 5 of theNames)
end tell

It behaved flawlessly.

Yvan KOENIG running Sierra 10.12.1 in French (VALLAURIS, France) samedi 10 décembre 2016 18:03:49

Mr Koenig, Mr Garvey, thank you so much for your attention and suggestions! I really appreciate it.

Mr Koenig, re: “play playlist (item 5 of theNames),” i know right??? but check it out…

Mr Garvey, heavens it has me stumped. The google produces examples of people using “play playlist” like http://alvinalexander.com/apple/itunes-applescript-examples-scripts-mac-reference

and i have tried a bunch of variations, including things like

 	 play playlist playlistMerged
	
	play track 1 of playlist playlistMerged
	
	activate
	set view of browser window 1 to playlist "Now Playing"
	play 

and I just can’t get a play!

my next theory when i’m back to the mini is: maybe iTunes treats playlists of “TV Shows” differently? I will try changing the video type to “Music Video” and see what happens…! [Edit: nothing happened!]

Thanks again, you are all fantastic!

Ӯ

When I write that a script behaved flawlessly, it’s because it did.
I ran it again and the history was :

[format]tell application “iTunes”
get name of every playlist
→ {“Bibliothèque”, “Musique”, “Vidéos”, “Films”, “Vidéos personnelles”, “Séries TV”, “Podcasts”, “iTunes U”, “Livres”, “Livres audio”, “PDF”, “Livres audio”, “Achats”, “Ajouté récemment”, “Ajouts récents”, “Années 90”, “Clips vidéo musicaux”, “Les 25 plus écoutés”, “Meilleur classement”, “Morceaux récents”, “Musique classique”, “Chansons - youtube”, “compilation #3”, “Compilation #4”, “Compilation #5”, “Danielle Messia”, “Économiseur d’écran des illustrations iTunes”, “Ipod Michèle”, “Jazz”, “Jean Ferrat”, “Ma Liste”, “Playlist sans titre”, “pour maman”, “pour maman 2”, “Purchased by koenigyvan@mac.com”, “Serge Reggiani”, “Stromae Racine carrée”, “Vidéos offertes par Apple”}
play playlist “Vidéos personnelles”
end tell[/format]

I must add an important feature:
[format]play playlist (item 5 of theNames)[/format]
is equivalent to
[format]play track 1 of playlist (item 5 of theNames)[/format]

Yvan KOENIG running Sierra 10.12.1 in French (VALLAURIS, France) samedi 10 décembre 2016 20:48:53

I apologize if there is a misunderstanding, Mr Koenig”i was not arguing.

“I know right” was merely to emphasize that the clear and simple script you offered should behave flawlessly; my screen shot was merely to demonstrate that for some obscure reason the script fails on my test machine. (To be clear, I only called out that particular line because AppleScript editor highlighted it as the offending code.)

I assure you, I appreciate everyone’s help and I am certainly not here to pick a fight with anyone!

(further, that example code works fine & instantly on my MacBookPro11,5 with macOS 10.12.1, but fails on the test machine… a mini2,1 with Mac OS X 10.7.5…)

Ӯ

My suggestion was only based on looking at the dictionary. I don’t use or script iTunes myself. But Yvan’s confirmed that the syntax is at least correct. (Thanks, Yvan.)

When I try running the script shown in your screenshot, I get exactly the same error ” but then all my default playlists are empty. If I try to play a playlist with a completely fictitious name, I get a different error. (“Can’t make some data into the expected type.”) This suggests (but doesn’t prove) that the problem stems from a playlist which exists but can’t be played for some reason. Is it definitely being populated?

Something I’ve noticed in Yvan’s clean-up of your script:

The outer repeat probably is useless, but if it’s removed, the the ‘exit repeat’ line should be removed as well.

i was suspicious of this too, and went through several steps to isolate an apparent (but possibly silly) cause.

The “Now Playing” playlist is being built correctly, you can even watch the tracks disappear and repopulate, correctly placing interstitials and the selections from the source Smart Playlist in order.

But the Script kept hanging on the “Parameter Error.”

I thought maybe the video type TV Show had some inherent play-once-and-stop quality, so i switched some files to Music Video. This made no difference to the script (still “parameter error”),

BUT the playlist would at least play in iTunes by hitting space bar or selecting play.

HOWEVER, the playlist seemed determined to shuffle.

On a hunch, i searched the options on the file to uncover “Skip While Shuffling””apparently enabled on all videos by default? I unchecked that, and now the script is able to run, populate, and PLAY… albeit inexplicably as a shuffled list. So, the script was hanging because it refused to play a shuffled list? and there appears to be no way to just tell it to Play the Playlist in order…? as I said, this is silly, which makes me think I have not found a solution, merely some kind of curious workaround.

On that note, I implemented a quick routine to play the playlist track-by-track in the script itself, which provides the added bonus of a definite end (no need for an “on idle” check to wait out the playlist). However, in a baffling twist, the tracks still seem determined to shuffle… It’s a crazy world.

The current mostly-functioning script it attached below. It is nicely streamlined, thanks to both you fine gentlemen for your patience.

I will keep working and keep you posted. drop a line with any additional insight.

set PlaylistTVShow to ({first item of my text_to_list((do shell script "/usr/local/bin/icalbuddy -eed -nc -b \"\" eventsNow"), return)} as text) --Get Current Calendar Event via iCalBuddy hasseg.org/icalBuddy

tell application "iTunes"
	--Shuffle based on "CK's Evenly-shuffled Playlists v0.6" by Charles Kelly http://www.manythings.org/mac/
	set playlistMerged to "Now Playing"
	set PlaylistInterstitials to "[ID-D]" -- Intersitials for the [D]aytime broadcast
	
	if (not (exists playlist playlistMerged)) then
		set playlistMerged to make new user playlist with properties {name:playlistMerged} -- if no playlist, make it
	else
		set playlistMerged to user playlist playlistMerged -- if playlist, clean it out
		delete tracks of playlistMerged
	end if
	
	set MergedTracks to {}
	repeat with i from 1 to (count of tracks of playlist PlaylistTVShow) -- length based on requested TV Show
		set theTrack to some track of playlist PlaylistInterstitials
		set enabled of (duplicate theTrack to playlistMerged) to true
		set MergedTracks to MergedTracks & (database ID of theTrack)
		set theTrack to track i of playlist PlaylistTVShow
		set enabled of (duplicate theTrack to playlistMerged) to true
		set MergedTracks to MergedTracks & (database ID of theTrack)
	end repeat
	
	activate
	set view of browser window 1 to playlistMerged
	tell application "System Events" to tell process "iTunes" to set value of attribute "AXFullScreen" of window 1 to true
	repeat with i from 1 to (count of tracks of playlistMerged)
		play track i of playlistMerged
	end repeat
	
	-- then, at end of playlist, display UpNext card or Test Pattern or something...
	
end tell

on text_to_list(txt, delim)
	set saveD to text item delimiters
	try
		set text item delimiters to {delim}
		set theList to every text item of txt
	on error
		set text item delimiters to saveD
	end try
	set text item delimiters to saveD
	return (theList)
end text_to_list

iTunes window showing playlist:

iCal window showing example schedule (not really “Bugs Bunny” all day, that’s just for testing)

Your very first instruction is a real mess.

set PlaylistTVShow to ({first item of my text_to_list((do shell script "/usr/local/bin/icalbuddy -eed -nc -b \"\" eventsNow"), return)} as text) --Get Current Calendar Event via iCalBuddy hasseg.org/icalBuddy

first item of my text_to_list. IS a text object.
you enclose it between curly brackets so you get a list containing a single object.
then you coerce this list as text

It would be more clear and efficient to edit it as :

set PlaylistTVShow to first item of my text_to_list((do shell script "/usr/local/bin/icalbuddy -eed -nc -b \"\" eventsNow"), return) 

It may be cleaned more with :

set PlaylistTVShow to first paragraph of (do shell script "/usr/local/bin/icalbuddy -eed -nc -b \"\" eventsNow")

which allow you to drop the text_to_list handler.

If you want to be sure that the shuffle menu item is disabled (in this case there is the checked character in front of it)

replace your instruction :

   tell application "System Events" to tell process "iTunes" to set value of attribute "AXFullScreen" of window 1 to true

by

set {mt, mi, ms} to {7, 16, 2}
tell application "System Events" to tell process "iTunes"
	set frontmost to true
	# disable the shuffle menu item
	tell menu bar 1 to tell menu bar item mt to ¬
		tell menu 1 to tell menu item mi to tell menu 1 to click menu item ms
	set value of attribute "AXFullScreen" of window 1 to true
end tell

In fact I don’t know exactly why some times it is enabled without any action.
Some times ago I got the same “odd” behavior.
I had a bad idea :
I deleted the “com.apple.iTunes.plist” preferences file AND the folder “com.apple.iTunes.savedState”.
The app retrieved its “normal” behavior.
Fine but at this time I don’t know which deletion killed the oddity.

Yvan KOENIG running Sierra 10.12.1 in French (VALLAURIS, France) dimanche 11 décembre 2016 13:47:03

I apologize, I was unable to guess that you tested on such an old operating system.
It seems that iTunes evolved - which is not really surprising.
I don’t have a machine running 10.7.5 but I have one running 10.9.5 and I will test the code in it.

Bingo, I think that I have the true explanation.

When I booted from my HD running 10.9.5, I got the error -50.
When I booted from my HD running 10.10.5, I got the error -50.

In both cases, the 5th playList named “Vidéos personnelles” in French was empty.
On my daily used HD, the same playlist contain two items which make the difference.

May you try to run:

tell application "iTunes"
	set theNames to name of playlists
	repeat with theIndex from 1 to count theNames
		if tracks of (playlist (item theIndex of theNames)) ≠ {} then
			play playlist (item theIndex of theNames)
			exit repeat
		end if
	end repeat
end tell

Yvan KOENIG running Sierra 10.12.1 in French (VALLAURIS, France) dimanche 11 décembre 2016 15:41:43

Mr Koenig,

I adore every contribution you’ve made”
even when you reveal that I am little better than a copy-n-paste hack! : )

this in particular is a lovely, clean bit of work, thank you so much”and I apologize for the original “real mess” (it made sense at some point… i think…)

set PlaylistTVShow to first paragraph of (do shell script "/usr/local/bin/icalbuddy -eed -nc -b \"\" eventsNow")

this is what’s creepy: the “Now Playing” playlist was definitely populated.

But something was making iTunes behave like it could not play it.

Both yourself and Mr Garvey hit upon the “empty playlist” point, like, iTunes was convinced there was nothing there it could play… That is why I started searching for Any Other Explanation, settling on my ersatz “change everything to a music video and make sure shuffle is off…”

I am not satisfied with my explanation; i cannot find anything that confirms or denies if iTunes treats playing a “TV Show” differently from playing a “Music Video.” But… my silly solution works for some reason: everything plays now. (Of course, that’s the sort of “I have no idea what I"m doing” solution that leads to sloppy code…)

I will keep investigating, and I will keep you posted.

Ӯ

I let the Dayparting script run Sunday and Monday and it worked great! with only a couple caveats…

Sometimes, an event would come up “” leaving the thePlaylistName empty. the was easily addressed but changing the Alert trigger to “1 minute after” to make sure the script was well within the event. I also added a failsafe by wrapping the get Event name block in a try and adding a Dead Air contingency.

In the interest of possible event collision (since the script just starts playlists and walks away), I added a quick “if already playing, do a fade-and-switch” thing.

My next step is make the script “universal,” able to play Videos or Music-with-Visualizer, depending on playlist type. Right now, it checks the name of the playlist for a musical note character, which is effective but inelegant. The Music-option simply plays through a playlist while showing the visualizer… I would like to make that more interesting, like, by continuing the fake-Station-ID gag, and maybe on-the-fly visualizer setting changes…

Here is the current 'Script, incorporating better variable names as suggested by Mr Koenig. Also, a couple screenshots of the iTunes and iCal setup, for fun and reference.

Ӯ

try
	set thePlaylistName to first paragraph of (do shell script "/usr/local/bin/icalbuddy -eed -nc -b \"\" eventsNow") -- Get Current Calendar Event via iCalBuddy hasseg.org/icalBuddy
on error
	set thePlaylistName to "♫ Dead Air" -- event blank for some reason? just play music 
end try

set theFirstCharacter to first character of thePlaylistName -- it'd be sexier if script could simply determine if Playlist has Video or Not...

tell application "iTunes"
	
	if theFirstCharacter is not "♫" then -- it's not music, shuffle video with station IDs...
		
		--Shuffle based on "CK's Evenly-shuffled Playlists v0.6" by Charles Kelly http://www.manythings.org/mac/
		set playlistMergedName to "Now Playing"
		set PlaylistInterstitialsName to "[ID-D]" -- Intersitials for the [D]aytime broadcast
		
		if (not (exists playlist playlistMergedName)) then
			set playlistMergedList to make new user playlist with properties {name:playlistMergedName} -- if no playlist, make it
		else
			set playlistMergedList to user playlist playlistMergedName -- if playlist, clean it out
			delete tracks of playlistMergedList
		end if
		
		set MergedTracks to {}
		repeat with i from 1 to (count of tracks of playlist thePlaylistName) -- length based on requested Show
			set theTrack to some track of playlist PlaylistInterstitialsName
			set enabled of (duplicate theTrack to playlistMergedList) to true
			set MergedTracks to MergedTracks & (database ID of theTrack)
			set theTrack to track i of playlist thePlaylistName
			set enabled of (duplicate theTrack to playlistMergedList) to true
			set MergedTracks to MergedTracks & (database ID of theTrack)
		end repeat
		
	else
		set playlistMergedList to user playlist thePlaylistName -- it's just music. -- still, be fun to have station ID, like, every fifth song.
		
	end if
	
	activate
	
	if player state is playing then
		set theVolume to sound volume
		my FadeOut(5, 0.5)
		stop
		set sound volume to theVolume
	end if
	
	set visible of browser window 1 to true
	set view of browser window 1 to playlistMergedList
	
	tell application "System Events" to tell process "iTunes" to set value of attribute "AXFullScreen" of window 1 to true
	
	play playlistMergedList
	if theFirstCharacter is "♫" then set visuals enabled to true -- it's music, so play the visualizer
	
end tell

to FadeOut(tick, thismany)
	tell application "iTunes"
		repeat
			if sound volume is less than or equal to tick then
				set sound volume to 0
				exit repeat
			end if
			set sound volume to ((sound volume) - tick)
			delay thismany
		end repeat
	end tell
end FadeOut

iTunes…

iCal…

i have devised…

	if (every file track of user playlist thePlaylistName whose video kind is music video) ≠ {} then

making the start of the script

try
	set thePlaylistName to first paragraph of (do shell script "/usr/local/bin/icalbuddy -eed -nc -b \"\" eventsNow") -- Get Current Calendar Event via iCalBuddy hasseg.org/icalBuddy
on error
	set thePlaylistName to "Dead Air" -- event blank for some reason? just play music 
end try

tell application "iTunes"
	
	if (every file track of user playlist thePlaylistName whose video kind is music video) ≠ {} then
		-- it's not music, shuffle video with station IDs...
		
		--Shuffle based on "CK's Evenly-shuffled Playlists v0.6" by Charles Kelly http://www.manythings.org/mac/

…which works. I expect there is a more elegant solution; I will keep experimenting.

Ӯ

This latest iteration will determine if the source playlist is Music or Video”Video playlists get an " interstitial" between each video; Music gets an “interstitial” every few songs, the rest of the time the iTunes Visualizer plays!

I’ve played with this all morning, and it works really well… except the transitions are uggggggggly.

Within a playlist, video-to-video works fine…

However, between “shows” there is a flash of the iTunes Browser Window, when it builds and starts to play”gross!

and the switch from “interstitial” back to visualizer always involves a flash of playlist window”gross!!!

i will now experiment with someway to circumvent or minimize that.

in the meantime, see what you think!

Ӯ

try
	set thePlaylistName to first paragraph of (do shell script "/usr/local/bin/icalbuddy -eed -nc -b \"\" eventsNow") -- Get Current Calendar Event via iCalBuddy hasseg.org/icalBuddy
on error
	set thePlaylistName to "Dead Air" -- event blank for some reason? just play music 
end try

tell application "iTunes"
	
	set playlistMergedName to "Now Playing"
	set PlaylistInterstitialsName to "[ID-D]" -- intersitials for the [D]aytime broadcast
	if ((hours of (current date)) > 21) or ((hours of (current date)) < 5) then set PlaylistInterstitialsName to "[ID-N]" --unless it's [N]ight
	
	if (not (exists playlist playlistMergedName)) then
		set playlistMergedList to make new user playlist with properties {name:playlistMergedName} -- if no playlist, make it
	else
		set playlistMergedList to user playlist playlistMergedName -- if playlist, clean it out
		delete tracks of playlistMergedList
	end if
	
	set theTrackCount to (count of tracks of playlist thePlaylistName) -- length based on requested Show
	set MergedTracks to {}
	
	if (every file track of user playlist thePlaylistName whose video kind is music video) ≠ {} then -- it's not music
		
		--Shuffle based on "CK's Evenly-shuffled Playlists v0.6" by Charles Kelly http://www.manythings.org/mac/
		repeat with i from 1 to theTrackCount
			set theTrack to some track of playlist PlaylistInterstitialsName
			set enabled of (duplicate theTrack to playlistMergedList) to true
			set MergedTracks to MergedTracks & (database ID of theTrack)
			set theTrack to track i of playlist thePlaylistName
			set enabled of (duplicate theTrack to playlistMergedList) to true
			set MergedTracks to MergedTracks & (database ID of theTrack)
		end repeat
		
	else -- it's music
		set i to 1
		repeat while i < theTrackCount
			set theTrack to some track of playlist PlaylistInterstitialsName
			set enabled of (duplicate theTrack to playlistMergedList) to true
			set MergedTracks to MergedTracks & (database ID of theTrack)
			
			set theNumberOfSongs to (random number from 3 to 7)
			repeat with aNumber from 0 to theNumberOfSongs
				try
					set theTrack to track (i + aNumber) of playlist thePlaylistName
					set enabled of (duplicate theTrack to playlistMergedList) to true
					set MergedTracks to MergedTracks & (database ID of theTrack)
				on error
					-- must be out of numbers so do nothing
				end try
			end repeat
			set i to i + theNumberOfSongs + 1
		end repeat
		
	end if
	
	activate
	
	if player state is playing then
		set theVolume to sound volume
		my FadeOut(5, 0.5)
		pause
		set sound volume to theVolume
	end if
	
	set visible of browser window 1 to true
	
	tell application "System Events" to tell process "iTunes" to set value of attribute "AXFullScreen" of window 1 to true
	
	set visuals enabled to true -- make sure iTunes Visualizer options are set to "Play Videos"
	
	play playlistMergedList
	
end tell

to FadeOut(tick, thismany)
	tell application "iTunes"
		repeat
			if sound volume is less than or equal to tick then
				set sound volume to 0
				exit repeat
			end if
			set sound volume to ((sound volume) - tick)
			delay thismany
		end repeat
	end tell
end FadeOut

Hola, amigos. I know it’s been a long time since I rapped at ya.

This up-to-the-minute version of my “dayparting” script performs a few different actions, based on the name of the iCal event; these include having QuickTime start or stop a video “test pattern,” as well as the original “generate a shuffled playlist” that started the project. There is also an event logging process that I have been using to keep track of functions.

This project was functional in time for christmas; i spent the time between christmas and new year’s eve playing with different functions and troubleshooting the existing processes.

This current version has been running for a a week with mostly good results. Sometimes events get called a little wrong, maybe QuickTime fails to start, maybe the value of attribute “AXFullScreen” is a freakin’ mystery. and there’s occasional flashes of iTunes between videos i[/i]. but it queues up The Muppet Show each day, and plays Cartoons to great effect.

(to be clear, I know this script is of ludicrously narrow function. i merely hope it inspires some unobvious solution in anyone else out there. Also, i just appreciate other eyes perusing my ersatz code” let me know what you think!)

Have fun!

if application "QuickTime Player" is running then StopQuicktime()

try
	set theEventName to first paragraph of (do shell script "/usr/local/bin/icalbuddy -eed -nc -b \"\" eventsNow") -- Get Current Calendar Event via iCalBuddy hasseg.org/icalBuddy
on error
	set theEventName to "Dead Air" -- problem? just play music 
end try

set TheEventType to the first character of theEventName -- possible characters include ★ ♥ ▶ ◼︎ ✱

if TheEventType is not "◼︎" and theEventName is not "Dead Air" then set ComingUp to GetNextEvent(theEventName)

if TheEventType is "◼︎" then set TheEventType to SignOff() -- stop playing things

if TheEventType is "â–¶" then set TheEventType to TestPattern() -- get ready to play things

if TheEventType is not "" then NowPlaying(theEventName) -- play things

LogThisAction("[Event "" & theEventName & "" Executed]")
LogThisAction("[up next "" & ComingUp & ""]")

on NowPlaying(thePlaylistName)
	tell application "iTunes"
		activate
		
		if player state is playing then
			set theVolume to sound volume
			my FadeOut(5, 0.5)
			pause
			set sound volume to theVolume
			my LogThisAction("paused iTunes to switch playlists")
		end if
		
		set playlistMergedName to "Now Playing"
		set PlaylistInterstitialsName to "[ID-D]" -- intersitials for the [D]aytime broadcast
		if ((hours of (current date)) > 21) or ((hours of (current date)) < 5) then set PlaylistInterstitialsName to "[ID-N]" --unless it's [N]ight
		
		if (not (exists playlist playlistMergedName)) then
			set playlistMergedList to make new user playlist with properties {name:playlistMergedName} -- if no playlist, make it
		else
			set playlistMergedList to user playlist playlistMergedName -- if playlist, clean it out
			delete tracks of playlistMergedList
		end if
		
		set theTrackCount to (count of tracks of playlist thePlaylistName) -- length based on requested Show
		set MergedTracks to {}
		
		if (every file track of user playlist thePlaylistName whose video kind is music video) ≠ {} then -- it's not music
			
			--Shuffle based on "CK's Evenly-shuffled Playlists v0.6" by Charles Kelly http://www.manythings.org/mac/
			repeat with i from 1 to theTrackCount
				set theTrack to some track of playlist PlaylistInterstitialsName
				set enabled of (duplicate theTrack to playlistMergedList) to true
				set MergedTracks to MergedTracks & (database ID of theTrack)
				set theTrack to track i of playlist thePlaylistName
				set enabled of (duplicate theTrack to playlistMergedList) to true
				set MergedTracks to MergedTracks & (database ID of theTrack)
			end repeat
			
		else -- it's music
			set i to 1
			repeat while i < theTrackCount
				set theTrack to some track of playlist PlaylistInterstitialsName
				set enabled of (duplicate theTrack to playlistMergedList) to true
				set MergedTracks to MergedTracks & (database ID of theTrack)
				
				set theNumberOfSongs to (random number from 3 to 7)
				repeat with aNumber from 0 to theNumberOfSongs
					try
						set theTrack to track (i + aNumber) of playlist thePlaylistName
						set enabled of (duplicate theTrack to playlistMergedList) to true
						set MergedTracks to MergedTracks & (database ID of theTrack)
					on error
						-- must be out of numbers so do nothing
					end try
				end repeat
				set i to i + theNumberOfSongs + 1
			end repeat
			
		end if
		
		try -- this sequence of try/error statements annoys me
			set visible of browser window 1 to true
		on error
			my LogThisAction("problem setting visible of broswer window.")
		end try
		
		try
			set view of browser window 1 to playlistMergedList
		on error
			my LogThisAction("problem setting view of browser window.")
		end try
		
		-- tell application "System Events" to tell process "iTunes" to set value of attribute "AXFullScreen" of window 1 to true
		set isFullScreen to false
		tell application "System Events" to tell process "iTunes" to set isFullScreen to value of attribute "AXFullScreen" of window 1
		if isFullScreen is false then
			tell application "System Events" to keystroke "f" using {command down, control down}
			delay 0.5
			my LogThisAction("(enabled fullscreen)")
		else
			my LogThisAction("(already fullscreen)")
		end if
		
		if visuals enabled is false then set visuals enabled to true -- make sure iTunes Visualizer options are set to "Play Videos"
		
		play playlistMergedList
		
		my LogThisAction("Now Playing " & thePlaylistName)
		my LogThisAction("Starting with " & (name of track 2 of playlistMergedList))
		
		tell application "Chiller" to run -- background app will wait until playlist finishes, then starts a "Filler" and quits itself.
		
	end tell
end NowPlaying

to FadeOut(tick, thismany)
	tell application "iTunes"
		repeat
			if sound volume is less than or equal to tick then
				set sound volume to 0
				exit repeat
			end if
			set sound volume to ((sound volume) - tick)
			delay thismany
		end repeat
	end tell
end FadeOut

to LogThisAction(themessage)
	set theLogFile to "TV-" & (do shell script "date  +'%d%b%Y'" as string) & ".log" -- make file named "TV-DayMonthYear.log"
	set theLine to (do shell script "date  +'%a %d-%b-%Y %H:%M'" as string) & " '" & themessage & "'" -- quoted $message to avoid trouble characters
	do shell script "echo " & theLine & " >> ~/Documents/" & theLogFile
end LogThisAction

to StopQuicktime()
	tell application "QuickTime Player"
		set theLogEventModifer to ""
		activate
		delay 0.5
		try
			set presenting of the front document to false
		on error
			my LogThisAction("problem turning off "presenting".")
			set theLogEventModifer to " maybe"
		end try
		delay 0.5
		try
			stop the front document
		on error
			my LogThisAction("problem stopping Movie.")
			set theLogEventModifer to " maybe"
		end try
		delay 0.5
		try
			close the front document
		on error
			my LogThisAction("problem closing Movie.")
			set theLogEventModifer to " maybe"
		end try
		quit
		my LogThisAction("Stopped Quicktime" & theLogEventModifer)
	end tell
end StopQuicktime

to SignOff()
	tell application "iTunes"
		set theLogEventModifer to ""
		activate
		delay 0.5
		if visuals enabled is true then set visuals enabled to false
		delay 0.5 -- all these sad delays because the script moves faster than the mini...
		tell application "System Events" to tell process "iTunes" to set value of attribute "AXFullScreen" of window 1 to false
		delay 0.5
		stop
		delay 0.5
		tell application "System Events" to keystroke "w" using command down
		my LogThisAction("Sign'd off iTunes" & theLogEventModifer)
	end tell
	return "" -- clear theEventType / skip to the end
end SignOff

to TestPattern()
	tell application "Finder" to set theTestPattern to some file of folder "Test Patterns" of folder "Movies" of home -- get random screen filler loop
	tell application "QuickTime Player"
		activate -- all these sad delays because the script moves faster than the mini...
		delay 0.5
		open theTestPattern
		delay 0.5
		set looping of the front document to true
		delay 0.5
		set presenting of the front document to true
		delay 0.5
		play the front document
		my LogThisAction("played test pattern " & theTestPattern)
	end tell
	return "" -- clear theEventType / skip to the end
end TestPattern

on GetNextEvent(theEventName)
	set theEventList to paragraphs of (do shell script "/usr/local/bin/icalbuddy -npn -nc -iep \"title\" -b \"\" eventsToday") -- via iCalBuddy hasseg.org/icalBuddy
	set NextEvent to ""
	repeat with i from 1 to count of theEventList
		if item i of theEventList is theEventName then set NextEvent to (item (i + 1) of theEventList)
	end repeat
	if the first character of NextEvent is "◼︎" then set NextEvent to "Tune in Tomorrow!"
	return NextEvent
end GetNextEvent

here is the current schedule…

and here it is in action.