Create a gist now

Instantly share code, notes, and snippets.

#!/usr/bin/env ruby
# encoding: UTF-8
pid = fork and (Process.detach(pid); exit) # Go to background.
require 'appscript'
SRC_MACRUBY_WAIT_FOR_PLAYER_NOTIFICATION = <<-RUBY
framework "Cocoa"
def playerInfo(notification); exit; end
NSDistributedNotificationCenter.defaultCenter.addObserver(self, selector:"playerInfo:", name:"com.apple.iTunes.playerInfo", object:nil)
NSRunLoop.currentRunLoop.run
RUBY
class << $itunes = Appscript::app("iTunes")
def wait_for_track_to_end(track)
@track_to_wait_for = track
wait_for_player_info_notification until track_to_wait_for_has_started_playing? && !track_to_wait_for_is_currently_playing?
end
private
def track_to_wait_for_is_currently_playing?
@track_to_wait_for == (current_track.get rescue nil)
end
def track_to_wait_for_has_started_playing?
@track_to_wait_for_has_started_playing ||= track_to_wait_for_is_currently_playing?
end
def wait_for_player_info_notification
system "macruby", "-e", SRC_MACRUBY_WAIT_FOR_PLAYER_NOTIFICATION
end
end
next_track = $itunes.selection.get.first or ($stderr.puts "no tracks selected"; exit 1)
$itunes.wait_for_track_to_end($itunes.current_track.get)
$itunes.play(next_track)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment