' =========
' FadeTunes
' =========
' Version 1.0.0.1 - January 26th 2012
' Copyright © Steve MacGuire 2012

' =======
' Licence
' =======
' This program is free software: you can redistribute it and/or modify it under the terms
' of the GNU General Public License as published by the Free Software Foundation, either
' version 3 of the License, or (at your option) any later version.

' This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
' without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
' See the GNU General Public License for more details.

' Please visit http://www.gnu.org/licenses/gpl-3.0-standalone.html to view the GNU GPLv3 licence.

' ===========
' Description
' ===========
' A VBScript to fade out, then stop iTunes playback
' Promted by this ASC thread: https://discussions.apple.com/thread/3687083?tstart=0

' =========
' ChangeLog 
' =========
' Version 1.0.0.1 - Initial version

' ==========
' To-do List
' ==========
' Add things to do

' =============================
' Declare constants & variables
' =============================
Option Explicit	        ' Declare all variables before use
Dim FadeTime,I,Interval,iTunes,Level,Min,PreFade


' Edit the following three variables to taste

PreFade=1               ' Duration in minutes (decimals allowed) before fade commences
FadeTime=15             ' Duration in minutes (decimals allowed) over which fade takes place
Min=0                   ' Volume to fade out to, resets to 0 if iTunes is already quieter


' ============
' Main program
' ============

' Create iTunes applicaton object
Set iTunes=CreateObject("iTunes.Application")
' Abort script if not playing or no volume
If iTunes.PlayerState<>1 or iTunes.SoundVolume=0 Then WScript.Quit 
' Pause for the prefade duration
WScript.Sleep PreFade*60000 
' Store current sound level
Level=iTunes.SoundVolume
' Make sure target level is less than current
If Min>=Level Or Min<0 Then Min=0
' Calculate interval to wait between each volume change
Interval=FadeTime*60000/(Level-Min)
' Initialise loop
I=Level
' Fade out
Do Until iTunes.PlayerState<>1 Or I<=Min
    ' Decrement level
    I=I-1
    ' Set new level
    iTunes.SoundVolume=I
    ' Pause for next change
    WScript.sleep Interval
Loop
' Pause playback
iTunes.Pause
' Make sure iTunes is paused before restoring level
WScript.sleep 100
' Restore original volume
iTunes.SoundVolume=Level

' ===================
' End of main program
' ===================

' That's all folks!    	'