Sunday, December 11, 2016

Control iTunes from command line

It is possible to control iTunes from command line. In order to do so you need to install itunes-remote.
Run npm install --global itunes-remote
Now you can send commands to iTunes.
First command needs to start with itunes-remote.
This would start itunes-remote session and all following commands don't have to starts with itunes-remote
any more.
Available commands are:
help, exit, play, pause, next, previous, back, search.
So you can run commands like this:
itunes-remote search moby
next
stop
Important to note here that you can only work with tracks that are part of your Library.
Command exit did not work for me. When you are using search for title that consists of multiple words
you should use single quotes like so:
itunes-remote search 'twisted transistor'
If you really want to you can start using this functionality inside of your scripts.
For example I added these lines to my pre-push git hook: 
 #!/usr/local/bin/ruby
 puts ("Pushing...pushing real good") 
 system("itunes-remote play") 
 sleep 3 
 system("itunes-remote search 'salt-n-pepa'") 
 sleep 5 system("kill $(ps -A | grep /Applications/iTunes.app/Contents/MacOS/iTunes | awk 'NR==1 {print $1}')")
What happens here is that this script will be executed on whenever I do a push to my repo. It would open iTunes,
wait 3 seconds (this is necessary for the process to get ready for commands) and would start playing song Push It
by Salt-N-Pepa because that is the only song by this band I have in my library. After 5 seconds the scripts
would kill iTunes process.