Created
March 17, 2015 12:58
-
-
Save mba811/d286cda1b841e15f3fe5 to your computer and use it in GitHub Desktop.
Download Youtube video (and subtitles, if video has them)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var request = require('request'); | |
| var querystring = require('querystring'); | |
| var fs = require('fs'); | |
| var xml2js = require("xml2js"); | |
| var ent = require('ent'); | |
| var video_id = 'IgKWPdJWuBQ'; | |
| var quality = 'hd720'; // hd1080, hd720, large, highres (original) | |
| Number.prototype.padLeft = function(n,str){ | |
| return Array(n-String(this).length+1).join(str||'0')+this; | |
| } | |
| function seconds2time(seconds) { | |
| var s = {} | |
| s.s = parseInt(seconds % 60).padLeft(2).toString() + "." + Number(((seconds % 60) % 1 * 1000).toFixed(3)).padLeft(3).toString(); | |
| s.m = parseInt((seconds / 60) % 60).padLeft(2); | |
| s.h = parseInt((seconds / 3600) % 24).padLeft(2); | |
| return [ | |
| s.h, s.m, s.s | |
| ].join(":"); | |
| } | |
| request('http://www.youtube.com/get_video_info?video_id=' + video_id, function(error, response, body){ | |
| var query = querystring.parse(body); | |
| try { | |
| if(query.url_encoded_fmt_stream_map){ | |
| var stream = null; | |
| var stream_map = query.url_encoded_fmt_stream_map.split(','); | |
| stream_map.forEach(function(senc){ | |
| var s = querystring.parse(senc); | |
| console.log(s); | |
| if((/^video\/mp4/).test(s.type) && s.quality === quality){ | |
| stream = s; | |
| } | |
| }); | |
| if(stream){ | |
| request(stream.url + '&signature=' + stream.sig).pipe(fs.createWriteStream(video_id + '.mp4')); | |
| if(query.ttsurl){ | |
| request(query.ttsurl + "&ts=" + new Date().getTime() + "&type=track&lang=en&format=1&kind=&name=", function(err, res, body){ | |
| if(!err && body){ | |
| var subtitles = ""; | |
| var subtitle_row = 1; | |
| var parser = new xml2js.Parser(); | |
| parser.parseString(body, function(err, result){ | |
| result.transcript.text.forEach(function(row){ | |
| var start = seconds2time(parseFloat(row['$'].start)); | |
| var end = seconds2time(Number((parseFloat(row['$'].start) + parseFloat(row['$'].dur)).toFixed(3))); | |
| subtitles += subtitle_row + "\n" + start + " --> " + end + "\n" + ent.decode(row['_']) + "\n\n"; | |
| subtitle_row++; | |
| }); | |
| fs.writeFileSync(video_id + '.srt', subtitles); | |
| }); | |
| } | |
| }); | |
| } | |
| } | |
| } | |
| } catch(err){ | |
| console.log(err); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment