Skip to content

Instantly share code, notes, and snippets.

@Hakon
Forked from clarkware/lyrics.rb
Created September 10, 2012 20:25
Show Gist options
  • Save Hakon/3693596 to your computer and use it in GitHub Desktop.
Save Hakon/3693596 to your computer and use it in GitHub Desktop.
Random Lyrics
#!/usr/bin/env ruby
# API Documentation at http://api.wikia.com/wiki/LyricWiki_API
require 'open-uri'
require 'json'
require 'tmpdir'
def itunes_song
`osascript -e 'tell application "iTunes" to (get name of current track) & "\n" & (get artist of current track)' 2>/dev/null`.split("\n")
end
def json_for(name, url)
temp_file = File.join(Dir.tmpdir, name)
if File.exists?(temp_file)
data = File.read(temp_file)
else
data = open(URI.escape(url)).read
File.open(temp_file, "w") { |f| f.puts data }
end
JSON.parse(data)
end
playing_song = itunes_song
if(playing_song.empty?)
artist = "Johnny Cash"
artist_json = json_for(artist, "http://lyrics.wikia.com/api.php?artist=#{artist}&fmt=realjson")
songs = artist_json["albums"].map { |a| a["songs"] }
song = songs.flatten.sample
else
song, artist = playing_song
end
song_json = json_for(song, "http://lyrics.wikia.com/api.php?artist=#{artist}&song=#{song}&fmt=realjson")
puts song_json["lyrics"].gsub("\n", ", ").squeeze
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment