りんごの備忘録

へなちょこポカ大生のへなちょこブログ

AppleScriptで曲の変わり目に通知が来るようにするまで(part2)

少し前の記事でiTunesの曲の変わり目に通知を入れるアプリケーションを作成しました.
rinringo429.hatenablog.com
しかしDockに表示される時と通知に使われるアイコンがデフォルトのアイコンなのでどうも見栄えがよろしくありません.そこでデフォルトのアイコンをアルバムアートワークに差し替えてみました.アルバムが変わるごとにアプリケーションのアイコンを変えることで通知のアイコンとDockのアイコンを変えてみました.かなりゴリ押しなのでご了承ください.

コード
property theName : ""
tell application "iTunes"
	if theName is "" then set theName to name of current track 
end tell

on idle
	tell application "iTunes"
		try
			set tmpName to name of current track
		on error
			set tmpName to theName
		end try
		if tmpName is not theName then
			if (count of artwork of current track) ≥ 1 then
				set artworkExists to true
				tell application "iTunes" to tell artwork 1 of current track
					set d to raw data
				end tell
				set thePath to ((path to pictures folder) as text) & "applet.iconset" 
				set theIconPath to thePath & ":icon_512x512.png"
				set icon_512 to open for access file (theIconPath) with write permission --アイコンの書き込み
				set eof icon_512 to 0
				write d to icon_512
				close access icon_512
				
				tell application "Image Events"
					launch
					set myImage to open file (theIconPath)
					save myImage in file (theIconPath) as PNG -- 上でアートワークを適当な拡張子で保存したためここでpng形式で再び上書き保存する
				end tell
				delay 1
				do shell script "sips -z 512 512 " & (POSIX path of theIconPath)
				do shell script "/usr/local/bin/convert " & (POSIX path of theIconPath) & " -alpha Set " & (POSIX path of theIconPath) --iconファイルを作成するためにImageMagicのconvertコマンドでalphaをオンにしている.(よく分かってない)
				do shell script "iconutil -c icns " & (POSIX path of thePath)
				do shell script "mv  " & POSIX path of (((path to pictures folder) as text)) & "applet.icns " & quoted form of "/Applications/Track Dialog.app/Contents/Resources/"

				try
					do shell script "mv \"/Applications/Track Dialog.app/Contents/changeTheArtwork\" \"/Applications/Track Dialog.app/\""
					delay 1
					do shell script "mv \"/Applications/Track Dialog.app/changeTheArtwork\" \"/Applications/Track Dialog.app/Contents/\""
					do shell script "killall Dock" --Dockのアイコンの更新
					delay 7 --あまり早すぎるとアルバムの変わり目の一曲目のアイコンが一つ前のアルバムのアートワークになってしまう
				end try
			else
				set artworkExists to false
			end if
			
			display notification "Album Name :" & album of current track with title "Album Artist :" & album artist of current track subtitle "Track Name :" & name of current track
			
		end if
		set theName to tmpName
		return 1
	end tell
end idle
使い方
  1. 上のコードを拡張子をapp,ハンドラを終了させないにチェックを入れて"Track Dialog"という名でアプリケーションフォルダに保存する.
  2. imageMagicのインストール
  3. picturesフォルダに"applet.iconset"という名のフォルダを作成
  4. Track Dialog のパッケージを表示しContentsフォルダの中に,"changeTheArtwork"という名の空のファイルを入れる
  5. 後はTrack Dialogを起動させるだけ
所感

そもそもアップルスクリプトでするべきではないのでは,,,,
圧倒的初心者なので根本的なことが分かってないためすごいゴリ押しをしてしまっている