public
anonymous / video.js
Last active

Node js on the fly video conversion

  • Download Gist
video.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
var child_process = require('child_process'),
sys = require('sys'),
http = require('http'),
parse = require('url').parse,
fs = require('fs');
var spawn = child_process.spawn;
var exec = child_process.exec;
 
function getDownloadUrl(video_url, resultCallback) {
exec('ruby youtube_link.rb ' + video_url,
function (error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
}
resultCallback(stdout);
});
}
 
function getYoutubeVideo(video_url, responseCallback) {
getDownloadUrl(video_url, function(downloadUrl) {
console.log("Got: " + downloadUrl)
var url = parse(downloadUrl);
var options = {
host: url.hostname,
port: url.port,
path: url.pathname + url.search
};
var req = http.request(options, function(res) {
responseCallback(res);
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
//http.get(options, responseCallback).on('error', function(e) {
// console.log("Got error: " + e.message);
//});
});
}
 
function spawnFfmpeg(exitCallback) {
var args = ['-i', 'pipe:0', '-f', 'mp3', '-ac', '2', '-ab', '128k', '-acodec', 'libmp3lame',
'pipe:1']
var ffmpeg = spawn('ffmpeg', args);
console.log('Spawning ffmpeg ' + args.join(' '));
 
ffmpeg.on('exit', exitCallback);
ffmpeg.stderr.on('data', function (data) {
console.log('grep stderr: ' + data);
});
return ffmpeg;
}
 
http.createServer(function (req, res) {
yt_url = parse(req.url, true).query['v'];
if(typeof yt_url == 'undefined') {
res.end("Specify url in 'v' query param");
return;
}
res.writeHead(200, {'Content-Type': 'audio/mpeg'});
var ffmpeg = spawnFfmpeg(
function (code) { // exit
console.log('child process exited with code ' + code);
res.end();
});
ffmpeg.stdout.pipe(res)
getYoutubeVideo(yt_url,
function(res) {
res.pipe(ffmpeg.stdin)
});
}).listen(8000);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.