Skip to content

Instantly share code, notes, and snippets.

@pioz
Last active August 29, 2015 13:56
Show Gist options
  • Save pioz/8836521 to your computer and use it in GitHub Desktop.
Save pioz/8836521 to your computer and use it in GitHub Desktop.
Download video as mp3 from youtube
#!/usr/bin/env ruby
require 'open-uri'
require 'cgi'
if ARGV[0].nil?
puts "usage: #{$0} YOUTUBE_VIDEO_ID"
puts " sample: #{$0} wG6G4XBnvLQ"
exit
end
link = "http://www.youtube.com/get_video_info?video_id=#{ARGV[0]}"
url = nil
info = open(link).read
info = CGI::parse(info)
title = info['title'][0]
info = info['url_encoded_fmt_stream_map'][0]
if info
info.split(',').each do |info|
info = CGI::parse(info)
if info['type'][0].include?('video/mp4')
url = "#{info['url'][0]}&signature=#{info['sig'][0]}"
break
end
end
end
if url
file = Tempfile.new(title)
file_size = nil
print 'Downloading video...'
data = open(url, content_length_proc: -> (t) {
file_size = t.to_f if t && t > 0
}, progress_proc: -> (s) {
if file_size
p = ((100.0 * s) / file_size).round
print "\b" * 80
print "Downloading video: #{p}%"
end
})
puts
file.write(data.read)
`ffmpeg -i '#{file.path}' -ab 128k '#{title}.mp3'`
file.close
file.unlink
else
puts 'Can\'t download video!'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment