Skip to content

Instantly share code, notes, and snippets.

@st44100
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st44100/53a2166bb417c6c54673 to your computer and use it in GitHub Desktop.
Save st44100/53a2166bb417c6c54673 to your computer and use it in GitHub Desktop.
Download Youtube Best Quality

Download Youtube Video Best Quality.

  • Download video@1080p without audio
  • Download audio@256k without video
  • Merge video and audio with ffmpeg
  • if 1080p video is not exists then select video quality automatically

Install and Usage:

$ brew install youtube-dl
$ brew install ffmpeg

$ ruby dl_youtube.rb YOUTUBE_URL
require 'shellwords'
url = ARGV[0]
unless url then
usage = "USAGE: ruby dl_youtube.rb <URL>"
print "No URL error", "\n"
print usage, "\n"
exit 1
end
res = `youtube-dl --get-filename #{url}`
filename = res.strip!
filename_base = Shellwords.shellescape(res.gsub(/\.mp4$/, ''))
if FileTest.exists?(filename) then
print "Already Downloaded!", "\n"
exit 1
end
p "#{filename}"
# Get Best Quality
formats = `youtube-dl -F #{url}`
format_id = 0
format_number = 0
formats.split(/\n/).each do |line|
f = line.split(/(^[0-9]+|mp4|[0-9]*p)/).map{ |s| s.strip }.select{|s| !s.empty? }
unless f[1] == 'mp4' then next end
if f[2].match(/[0-9]+p$/) and f[2].to_i > format_number
format_id = f[0].to_i
format_number = f[2].to_i
end
end
print "Video Quality: #{format_number}p", "\n"
res_video_hi = system("youtube-dl -f 137 #{url}")
if res_video_hi then
res_audio = system("youtube-dl -f 141 #{url}")
p res_audio
else
res_video = system("youtube-dl #{url}")
p res_video
exit 1
end
unless res_audio
exit 1
end
res_ffmpeg = system("ffmpeg -i #{filename_base}.mp4 -i #{filename_base}.m4a #{filename_base}.out.mp4")
p res_ffmpeg
if res_ffmpeg then
File.delete("#{filename_base}.mp4")
File.delete("#{filename_base}.m4a")
File.rename("#{filename_base}.out.mp4", "#{filename_base}.mp4")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment