Skip to content

Instantly share code, notes, and snippets.

@electronicbites
Created February 9, 2009 10:35
Show Gist options
  • Save electronicbites/60738 to your computer and use it in GitHub Desktop.
Save electronicbites/60738 to your computer and use it in GitHub Desktop.
get the duration of a youtube video
require 'rubygems'
require 'hpricot'
require 'net/http'
HOST = "gdata.youtube.com"
SITE = "/feeds/api"
def parse_duration(xml)
result = 0
(xml/'entry').each do |entry|
result = (entry/'yt:duration').first.attributes["seconds"].to_i
end
result
end
def duration(youtubeid)
request = Net::HTTP::Get.new("#{SITE}/videos?q=#{youtubeid}&safeSearch=none")
request.add_field 'GData-Version', '2'
Net::HTTP.start("#{HOST}", 80) do |http|
response = http.request(request)
xml = Hpricot(response.body)
result = parse_duration(xml)
end
end
puts duration('001Vzudt-xo')
puts duration('0_0_1xD_T2k')
puts duration('001XYCqJU-Q')
puts duration('00lFrOufbYY')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment