DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

David has posted 23 posts at DZone. View Full User Profile

Automating And Managing ITunes With Ruby

07.24.2007
| 3458 views |
  • submit to reddit
        From the <a href="http://rubyonwindows.blogspot.com">Ruby on Windows</a> blog.
#   connect to the iTunes application object
require 'win32ole'
itunes = WIN32OLE.new('iTunes.Application')

#   place iTunes into MiniPlayer mode
itunes.BrowserWindow.MiniPlayer = true

#   toggle the play/pause setting
itunes.PlayPause

#    increase or decrease volume
itunes.SoundVolume = itunes.SoundVolume + 50
itunes.SoundVolume = itunes.SoundVolume - 25

#   go to previous or next track
itunes.PreviousTrack
itunes.NextTrack

#   grab the entire library playlist
library = itunes.LibraryPlaylist
tracks = library.Tracks

#   select and play a song by name
song = tracks.ItemByName('At Long Last Love')
song.Play

#   search for tracks
artist_tracks = library.Search('Sinatra', 2)
album_tracks = library.Search('Come Fly With Me', 3)
title_tracks = library.Search('Fly Me To The Moon', 5)

#   add all track objects to a ruby array
songs = []
for track in tracks
    songs << track
end

#   sort the songs array
songs = songs.sort_by{|song| [song.Artist, song.Year, song.Album, song.TrackNumber]}

#   iterate over the songs collection
songs.each do |song|
    puts [song.Artist, song.Year, song.Album, song.TrackNumber, song.Name, song.Time].join("\t")
end

#   create a new playlist and add songs
playlist = itunes.CreatePlaylist("My New Playlist")
song = tracks.ItemByName('At Long Last Love')
playlist.AddTrack(song)

#   add all playlist objects to a ruby array
playlists = []
itunes.Sources.each do |source|
    source.PlayLists.each do |playlist|
        playlists << playlist
    end
end

#   iterate over the collection of playlist objects
for playlist in playlists do
    puts playlist.Name
end

#   select a playlist by name, and play the first track
playlist = itunes.Sources.ItemByName('Library').Playlists.ItemByName('All Sinatra')
playlist.PlayFirstTrack

#   exit the iTunes application
itunes.Quit
Further details can be found <a href="http://rubyonwindows.blogspot.com/2007/07/automating-and-managing-itunes-with.html">here</a>.