Skip to content

Instantly share code, notes, and snippets.

@JorenSix
Created February 22, 2013 15:48
Show Gist options
  • Save JorenSix/5014344 to your computer and use it in GitHub Desktop.
Save JorenSix/5014344 to your computer and use it in GitHub Desktop.
A Spotify music quiz, implemented in ruby.
#!/bin/ruby
#
# Implements a simple music quiz.
#
# With a list of correct
# answers and a button, attached via serial. When the button
# is pressed, the meta data of the currently playing song in
# Spotify is checked, and if the currently playing song is
# in the list of correct songs a 'winner' sound file is played
# using aplay. If the currenlty playing song is not correct, a
# sad trombone sounds, shaming the button presser for his or her
# lack of cultural knowledge, in public, which is, to date, the
# most favorable of shaming eeh modalities. The previous, sentence,
# might contain to much commas. I might be a bit drunk, perhaps.
require 'rubygems'
require 'serialport'
device = "/dev/tty.usbserial-A4001nL5"
baudrate = 9600
sp = SerialPort.new(device,baudrate)
now_playing_command="./now_playing.osascript"
#Wrong answer: sad trombone
sad_trombone="sad_trombone.wav"
#Congratulations you win!!
winner="winner.wav"
#Invalid answer
cheater="cheater.wav"
# A list of correct titles, this assumes no titles
# appear twice in your playlist, a reasonable assumption
correct_answer_list=[
"It's My Life",
"Forever Young",
"I Want To Break Free - 2011 Remaster",
"Shout - Edit",
"Wrapped Around Your Finger - 2003 Stereo Remastered Version",
"Purple Rain",
"The Killing Moon [Ocean Rain / Expanded]",
"Tonight",
"Owner Of A Lonely Heart",
"99 Luftballons",
"Here Comes The Rain Again"]
# Parse the meta data (| is the separator)
def parse_result(result)
result =~ /^(.+) \| (.+) \| (.+) \| .*$/
[$1,$2,$3]
end
#Play a wav file with aplay or afplay
def play(filename)
puts "play " + filename
spawn "afplay \"#{filename}\""
end
# Make the answer list a hash for quick lookup
# premature optimization, i know, but hey.
correct_answers= Hash.new
correct_answer_list.each do |correct|
correct_answers[correct] = true
end
# This stores if somebody has
# already answered for this song
responded_to = Hash.new
while true do
# Wait for a button press
data = sp.readline
# Fetch meta data about the currently
# playing song
result = `#{now_playing_command}`
# Parse the meta data
title,artist,album = parse_result(result)
#Title is hash key, should be unique within playlist
key = title
if responded_to.has_key? key
puts "Already answered: you cheater"
play cheater
elsif correct_answers.has_key? key
puts "Correct answers: woohoo"
responded_to[key]=true
play winner
else
puts "Incorrect answer: sad trombone"
responded_to[key]=true
play sad_trombone
end
puts key
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment