示例#1
0
 getInfo(url, function(err, info) {
     var stream = ytdl(url);
     var mp3Path = info.title;
     var length = info.length_seconds;
     mp3Path = sanitizeFile(mp3Path) + '.mp3';
     if (options.dir) {
         mp3Path = path.join(options.dir, mp3Path);
     }
     console.log('Starting downloading ', info.title);
     var now = Date.now();
     new ffmpeg({source: stream}).audioBitrate(192).audioChannels(2).noVideo().outputFormat('mp3')
         .on('error', function(err) {
             console.log('Error converting', err);
             callback(err);
         })
         .on('progress', function(progress) {
             var timemark = progress.timemark;
             var time = timemark.split(':');
             var seconds = time[0]*60*60 + time[1]*60 + time[2].split('.')[0];
             console.log(info.title + ' - ' + Number((seconds/length).toFixed(1))+ '%');
         })
         .on('end', function() {
             console.log('Finished saving ' + info.title, 'Took:', Math.floor((Date.now() - now)/1000), 'seconds');
             callback(null, mp3Path);
         })
         .save(mp3Path);
 });
示例#2
0
	download: function(videoId) {
		
		var stream = ytdl('https://www.youtube.com/watch?v=' + videoId)
  			.pipe(fs.createWriteStream('assets/video/'+ videoId +'.mp4'));

		return stream;
	},
示例#3
0
文件: app.js 项目: devinhaber/OctoBot
 member.voiceChannel.join().then((connection) => {
     console.log("Playing video at url " + args[1] + " in channel " + member.voiceChannel.name)
     ytdl(args[1], { filter: function(format) { return format.container === 'mp4' && !format.encoding; } }).pipe(fs.createWriteStream('./sounds/temp.mp3')).on('finish', () => {
         dispatcher = connection.playFile('./sounds/temp.mp3', {'volume': config.volume, 'seek': seek});
         dispatcher.once('end', () => {currentlyplaying = false; connection.disconnect()});
     });
 }).catch((error) => {console.log("Error joining voice channel: " + error); currentlyplaying = false});
示例#4
0
var TubeStream = function(uri) {
  var self = this;
  EventEmitter.call(self);

  self.opt = {
    videoFormat: 'mp4',
    quality: 'lowest',
    audioFormat: 'mp3',
    applyOptions: function() {}
  };

  self.video = ytdl(uri, {
    filter: self.filterVideo,
    quality: self.opt.quality
  });

  self.video.on('info', function(data) {
    console.log('TubeStream Info: ' + data.title);
    self.emit('info', data);
  });

  self.video.on('finish', function() {
    self.emit('finish');
  });

  self.video.on('end', function() {
    self.emit('end');
  });

  self.filterVideo = function(format) {
    return format.container === (self.opt.videoFormat);
  }

  self._stream = self.opt.file ? fs.createWriteStream(self.opt.file) : through();

  self.ffmpeg = new FFmpeg(self.video);
  self.opt.applyOptions(self.ffmpeg);
  self.output = self.ffmpeg
    .format(self.opt.audioFormat)
    .pipe(self._stream);

  self.output.on('error', function(video) {
    self.video.end.bind(video);
    self.emit('error', video);
  });

  self.output.on('unpipe', function(source) {
    self.emit('unpipe', source);
  });

  self.stream = function() {
    return self._stream;
  };

  self.pipe = function(stream) {
    return self._stream.pipe(stream);
  };

};
示例#5
0
Track.prototype.stream = function() {
  return ytdl(this.url, {
    filter: format => {
      return format.container === 'mp4';
    },
    quality: 'lowest'
  });
}
示例#6
0
文件: bot.js 项目: shmurr/SBot
			.then(connection => {
				for(i = 0; i < queue.length; i++) {
					const audio = connection.playStream(ytdl(queue[i]), {volume: '0.25'});
					message.channel.sendMessage('Now playing ' + input +' !')
					audio.on('end', () => {
						voiceChannel.leave();
				})};
			});
示例#7
0
client.on('message', msg => {

	if (msg.author.bot) return;

	if (msg.channel.type == "dm" || msg.channel.type == "group"){

		let guild = client.guilds.find(guild => {return guild.name == 'GooseHead v2'});
		let textChannel = guild.channels.find(channel => {return channel.name == 'general'});
		
		textChannel.send(msg.content);
		return;

	}
	
	if (msg.channel.name == "mr-meeseeks"){

		if (msg.content.startsWith("http")){
						
			if (ytdl.validateURL(msg.content)){

				let stream = ytdl(msg.content, {filter: 'audioonly'});
				let time = tools.decodeURL(msg.content, "t");
				let seek = time ? {seek: tools.convertTime(time)} : {};
				pushAction({msg: msg, song: {stream: stream, seek: seek}});

			} else {
				console.log('URL non valide : ' + msg.content);
			}

		} else if (msg.content == "help"){

			pushAction({msg: msg, song: "rick/rick06.mp3", text: Object.keys(usercmds).sort().join(" ")});

		} else if (msg.content == "tg"){

			if (msg.guild.voiceConnection){
				msg.guild.voiceConnection.disconnect();
			}

		} else if (msg.content == "random"){

			let randomCommand = Object.keys(usercmds)[Math.floor((Math.random() * Object.keys(usercmds).length) + 1) - 1];
			executeCommand(msg, usercmds[randomCommand]);

		} else {

			let args = msg.content.toLowerCase().split(' ');
			let keywordsUsed = Object.keys(usercmds).filter(cmd => {return args.includes(cmd)});
			if (keywordsUsed.length > 0){
				let randomKeyword = keywordsUsed[Math.floor((Math.random() * keywordsUsed.length) + 1) - 1];
				executeCommand(msg, usercmds[randomKeyword]);
			}

		}
		
	}

});
示例#8
0
 return new Promise((resolve, reject) => {
     let stream = ytdl(this.link, {filter: 'audioonly'}).on('error', err => {
         if(err) {
             return reject(err);
         }
         console.log(`Error getting yt song stream: ${err}`);
         throw err;
     });
     return resolve(stream);
 });
示例#9
0
Player.prototype.playYoutube = function(url) {
	this.dl = ytdl(url, {
		filter: function(format) {
			return format.container === 'mp4';
		}
	});

	this.stream = ffmpeg(this.dl).format('mp3');
	this.stream.pipe(this.decoder);
};
示例#10
0
文件: app.js 项目: devinhaber/OctoBot
function executeMessage(cmd) {
    if (cmd.content == '!help') {
        cmd.channel.sendMessage(config.helpMessage);
    } else if (cmd.content.substring(0,5) == "!play") {
        cmd.guild.fetchMember(cmd.author).then((member) => {
            playFile(member.voiceChannel, cmd.content.substring(6));
        })
    } else if (cmd.content == '!stop') {
        console.log("Stopping bot playback")
        currentlyplaying = false;
        bot.voiceConnections.every((connection) => {
            connection.disconnect();
        });
    } else if (cmd.content == '!remaining') {
        // Probably won't work on windows. Whatever
        disk.check('/', (err, info) => {
            if (err) {console.log(err);}
            else {
                cmd.channel.sendMessage(info.free + ' space free out of ' + info.total + ' total.');
            }
        })
    } else if (cmd.content.substring(0,8) == '!youtube') {
        var args = cmd.content.split(" ")
        if (args.length >= 4 && args[1] == "save") {
            console.log("Saving video at url " + args[2] + " as " + args[3])
            ytdl(args[2], { filter: function(format) { return format.container === 'mp4' && !format.encoding; } }).pipe(fs.createWriteStream('./sounds/' + args[3] + '.mp3'));
            return;
        }
        if (args.length >= 2 && currentlyplaying == false) {
            currentlyplaying = true;
            seek = 0;
            if (args.length > 2) {
                seek = parseInt(args[2]);
            }
            cmd.guild.fetchMember(cmd.author).then((member) => {
                member.voiceChannel.join().then((connection) => {
                    console.log("Playing video at url " + args[1] + " in channel " + member.voiceChannel.name)
                    ytdl(args[1], { filter: function(format) { return format.container === 'mp4' && !format.encoding; } }).pipe(fs.createWriteStream('./sounds/temp.mp3')).on('finish', () => {
                        dispatcher = connection.playFile('./sounds/temp.mp3', {'volume': config.volume, 'seek': seek});
                        dispatcher.once('end', () => {currentlyplaying = false; connection.disconnect()});
                    });
                }).catch((error) => {console.log("Error joining voice channel: " + error); currentlyplaying = false});
            });
        } 
    } else if (cmd.content == '!sounds') {
            fs.readdir('./sounds', (err, files) => {
                if (err) {console.log(err)} else {
                    cmd.channel.sendMessage(files.join(", "));
                }
            })
    } else if (cmd.content == '!smug'){
        postSmugAnimeFace(cmd);
        return;
    }
}
示例#11
0
 return new Bluebird(function(resolve, reject)
 {
     var ASSETS_DIRECTORY = path.join(__dirname, "/../assets")
     if(!fs.existsSync(ASSETS_DIRECTORY))
     {
         fs.mkdir(ASSETS_DIRECTORY)
     }        
     
     var file_path = path.join(ASSETS_DIRECTORY, asset_id + ".flv")
     var youtube_url = "http://www.youtube.com/watch?v=" + youtube_id
     updateAsset({"youtube_id": youtube_id, "youtube_url": youtube_url})
     
     var downloading = YoutubeDownloader(youtube_url, {quality: 5})
     
     downloading.on("info", function(info, format)
     {
         if(info.title)
         {
             updateAsset({"title": info.title})
         }
         if(info.length_seconds)
         {
             updateAsset({"length": info.length_seconds})
         }
         if(info.thumbnail_url)
         {
             updateAsset({"thumbnail": info.thumbnail_url})
         }
         
         var current_amount = 0
         var total_amount = format.size
         downloading.on("data", function(data)
         {
             current_amount += data.length
             var progress = (current_amount / total_amount) * 100
             updateAsset({"progress": progress})
         })
     })
     
     downloading.on("error", function(error)
     {
         reject(error)
     })
     
     downloading.on("end", function()
     {
         updateAsset({"files": {"flv": file_path}}).then(function(asset)
         {
             resolve(asset)
         })
     })
     
     downloading.pipe(fs.createWriteStream(file_path))
 })
示例#12
0
 query(query_request, function (music_code, title) {
     title6 = title;
     console.log("TITLE", title);
     ytdl("http://www.youtube.com/watch?v=" + music_code)
         .pipe(fs.createWriteStream("public/output_music/" + query_request + ".mp3"))
         .on("close", function () {
             response.render('result.html', {
                 titles: title6,
                 query_strings: query_request
             });
         });
 });
app.post('/convert',function(req,res){
	
	var url = req.body.url;
	var outname = 'video.flv';
	url = url.replace(/\s+/g, '');
	console.log(url);
	res.setHeader('X-File-Name', outname);
	res.setHeader('Content-disposition', 'attachment; filename=' + outname);
	res.setHeader('Content-type', mime.lookup(outname));
	ytdl(url).pipe(res);
	
});
示例#14
0
function play(bot) {
  try {
    let stream = youtube(playList[0], {filter: 'audioonly'})
    stream.on('info', function(info) {
      if (info.length_seconds < 600) {
        bot.sendMessage(textMusicChannel, config.strings[i18n.language].nowListening + info.title, function (error) {
          if (error) {
            LOGGER.LOG(error)
          }
          bot.voiceConnection.playRawStream(stream, {volume : 0.3 }, function (error, streamIntent) {
            streamIntent.on("error", function (error) {
              LOGGER.LOG(`error : ${error}`);
            });
            streamIntent.on("time", function (time) {
              notPlaying = false;
            });
            streamIntent.on("end", function () {
              playList.shift();
              if (playList.length >= 1) {
                setTimeout (function() {
                  play(bot);
                }, 500);
              } else {
                playList = [];
                notPlaying = true;
                return 0;
              }
            });
          });
        });
      } else {
        bot.sendMessage(textMusicChannel, config.strings[i18n.language].musicLengthKO);
        playList.shift();
        if (playList.length >= 1) {
          setTimeout (function() {
            play(bot);
          }, 500);
        } else {
          playList = [];
          notPlaying = true;
          return 0;
        }
      }
    });
  } catch (e) {
    LOGGER.LOG(e);
    playList = [];
    notPlaying = true;
  }
  return 0;
}
        ytdl.getInfo(videoUrl, function(err, info){

            var videoTitle = info.title.replace(/"/g, '').replace(/'/g, '').replace(/\//g, '').replace(/\?/g, '');
            var artist = "Unknown";
            var title = "Unknown";

            if (videoTitle.indexOf("-") > -1) {
                var temp = videoTitle.split("-");
                if (temp.length >= 2) {
                    artist = temp[0].trim();
                    title = temp[1].trim();
                }
            } else {
                title = videoTitle;
            }

            var stream = ytdl(videoUrl, {
                quality: self.youtubeVideoQuality
            });

            var fileName = self.outputPath + '/' + videoTitle + '.mp3';
            var startTimestamp = new Date().getTime();

            var proc = new ffmpeg({
                source: stream
            })
                .audioBitrate(info.formats[0].audioBitrate)
                .withAudioCodec('libmp3lame')
                .toFormat('mp3')
                .outputOptions('-id3v2_version', '4')
                .outputOptions('-metadata', 'title=' + title)
                .outputOptions('-metadata', 'artist=' + artist)
                .on('error', function(err) {
                    console.log('An error occurred: ' + err.message);
                    callback(err.message, null);
                })
                .on('end', function() {
                    //console.log('Processing finished !');
                    callback(null, {
                        "file": fileName,
                        "videoId": videoId,
                        "youtubeUrl": videoUrl,
                        "videoTitle": videoTitle,
                        "artist": artist,
                        "title": title,
                        "took": (new Date().getTime()-startTimestamp)
                    });
                })
                .saveToFile(fileName);

        });
示例#16
0
 function download(id, filePath, callback) {
   ytdl(`http://www.youtube.com/watch?v=${id}`, {
     filter: mp4Filter,
   })
   .on("error", function(err) {
     fs.unlink(filePath)
     callback(err)
   })
   .on("finish", function() {
     console.log("finish")
     callback()
   })
   .pipe(fs.createWriteStream(filePath))
 }
  parsedHTML('.pl-video-title-link').map(function(i, link) {
    var url = $(link).attr('href');
    var title = $(link).text().trim();

    //console.log(title + "," + url);

		var fileName = title.replace(/\W/g, "_").toLowerCase()+ ".flv";
	
		console.log("downloading to fileName: " + fileName + " from url: " + url+ "<<");
	
		ytdl(url)
  		.pipe(fs.createWriteStream(fileName));
  
  });
示例#18
0
Downloader.prototype._downloadToStream = function (format, info, options) {
  var readStream = ytdl(options.url, {
    format: format
  });

  // Display progress only if called from the command line...
  if (options.cli) {
    readStream.on('info', function (streamInfo, streamFormat) {

      // Convert the string value to a true integer...
      streamFormat.size = parseInt(streamFormat.size);

      // Create progress bar.
      var bar = new ProgressBar('Downloading ' + format.type.substring(0, format.type.indexOf('/')) + '... :bar :percent (:etas remaining)', {
        width: 40,
        total: streamFormat.size,
        complete: '\u001b[42m \u001b[0m',
        incomplete: '\u001b[41m \u001b[0m',
        clear: true
      });

      // Keep track of progress while limiting draw calls...
      var batchTotal = 0;
      var totalRead = 0;
      var minTime = 100;

      var prevTime = +new Date();

      readStream.on('data', function (streamData) {
        totalRead += streamData.length;
        batchTotal += streamData.length;

        var isComplete = totalRead === streamFormat.size;

        var currTime = +new Date();
        var shouldUpdate = ((currTime - prevTime) > minTime);

        // Update on an interval or if complete...
        if (shouldUpdate || isComplete) {
          prevTime = currTime;

          bar.tick(batchTotal);
          batchTotal = 0;
        }
      });
    });
  }

  return readStream;
};
 async run(msg, args) {
     let bot = msg.client;
     let voiceChannel = msg.member.voice.channel;
     const streamOptions = {
         volume: .5
     };
     if (voiceChannel) {
         if (args.get('sound') === undefined) {
             const count = await Sounds.count();
             const random = Math.floor(Math.random() * count);
             const sound = await Sounds.findOne().skip(random);
             if (sound) {
                 let con = await this.connectToVoiceChannel(bot, voiceChannel);
                 if (con) {
                     return this.playSound(sound, msg.member, con);
                 }
             }
         } 
         else if (/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/.test(args.get('sound'))) {
             let con = await this.connectToVoiceChannel(bot, voiceChannel);
             if (con) {
                 try {
                     con.play(ytdl(args.get('sound'), {
                         filter: 'audioonly',
                         begin: args.get('time') ? args.get('time') : 0 + 's'
                     }), streamOptions);
                 } catch (err) {
                     console.error(err);
                 }
             }
         } else {
             const sound = await Sounds.findOne({
                 "key": {
                     $regex: new RegExp("^" + args.get('sound').toLowerCase() + "$", "i")
                 }
             });
             if (sound) {
                 let con = await this.connectToVoiceChannel(bot, voiceChannel);
                 if (con) {
                     this.playSound(sound, msg.member, con);
                 }
             } else {
                 msg.reply("Sound not found");
             }
         }
     } else {
         msg.reply("You must be in a Voice channel to play a sound");
     }
 }
示例#20
0
function download(url, title, message) {
  var songname = path.resolve(__dirname, '../songs') + '/' + Date.now() + '.mp3';
  var options = ({filter: 'audioonly', quality: 'highest'});
  var stream = dl(url, options);
  //FIXME: Electron seems to have an issue with yt-dl-core
  stream.pipe(fs.createWriteStream(songname));

  stream.on('end', function () {
    message.bot.sendMessage({
      to: message.channel,
      message: 'Done downloading ' + title
    });
    queue.add(songname, title);
  });
}
示例#21
0
 getJSON(path.join(options.path, 'items', file), function(data) {
     var videoId = data.contentDetails.videoId;
     var url = 'https://www.youtube.com/watch?v=' + videoId;
     var file = fs.createWriteStream(path.join(options.path, 'mp3s', videoId + '.mp3'));
     console.log('Downloading ' + videoId);
     
     ytdl(url, OPTIONS).pipe(file);
     file.on('finish', function() {
         finished++;
         console.log('Finished downloading ' + videoId + ' (' + finished + '/' + String(files.length) + ')');
         if (finished === files.length) {
             callback();
         }
     });
 });
示例#22
0
 function playMusic(channel, video) {
     let audioStream = ytdl(getYoutubeLink(video.link), {filter: 'audioonly'});
     let voiceHandler = bot.audio.connection.playStream(audioStream, {volume: 0.8});
     voiceHandler.on("debug", msg => {console.log(msg)});
     voiceHandler.on("error", v=> console.log(v));
     voiceHandler.on("start", v => {
         bot.audio.playing = true;
         channel.sendMessage("Now Playing: " + getYoutubeLink(video.link) + "\n");
     });
     voiceHandler.once("end", rtn => {
         channel.sendMessage("Song stopped.");
         bot.audio.playing = playNext(channel);
         voiceHandler = null;
     });
 }
示例#23
0
文件: gif.js 项目: uttpal/tube2gif
 return new Promise((resolve, reject) => {
   const stream = ytdl(video.url);
   stream.on('info', (meta) => {
     const videos = _.sortBy(_.filter(meta.formats, format => format.container === 'mp4'
       && (parseInt(format.quality_label, 10) || parseInt(format.resolution, 10))),
       [o => parseInt(o.quality_label, 10) || parseInt(o.resolution, 10)]);
     const options = {
       url: videos[parseInt(videos.length / 4, 10)].url,
       filename: getFileName(meta, video),
       from: video.start,
       duration: video.duration,
     };
     callFFmpeg(options)
       .then(() => resolve(options.filename.substr(9)))
       .catch(reject);
   });
 });
 function(callback) {
   ffmpeg(ytdl(url, {
     quality: "highest"
     }))
     .noVideo()
     .audioCodec('libmp3lame')
     .on('start', function() {
       console.log("Started converting Youtube movie to mp3");
     })
     .on('end', function() {
       callback(false);
     })
     .on('error', function(err) {
       callback(err);
     })
     .save(location);
 }
示例#25
-1
 .then(conn => {
   con = conn;
   msg.reply('done');
   disp = conn.playStream(ytdl(song, {filter:'audioonly'}), { passes : 3 });
   conn.player.on('debug', console.log);
   conn.player.on('error', err => console.log(123, err));
 })
示例#26
-1
 guilds[message.guild.id].voiceChannel.join().then(function (connection) {
     stream = ytdl("https://www.youtube.com/watch?v=" + id, {
         filter: 'audioonly'
     });
     guilds[message.guild.id].skipReq = 0;
     guilds[message.guild.id].skippers = [];
     guilds[message.guild.id].dispatcher = connection.playStream(stream);
     guilds[message.guild.id].dispatcher.on('end', function () {
         guilds[message.guild.id].skipReq = 0;
         guilds[message.guild.id].skippers = [];
         guilds[message.guild.id].queue.shift();
         guilds[message.guild.id].queueNames.shift();
         guilds[message.guild.id].queueTimes.shift();
         guilds[message.guild.id].queueAdders.shift();
         if (guilds[message.guild.id].queue.length === 0) {
             guilds[message.guild.id].queue = [];
             guilds[message.guild.id].queueNames = [];
             guilds[message.guild.id].queueTimes = [];
             guilds[message.guild.id].queueAdders = [];
             guilds[message.guild.id].isPlaying = false;
             guilds[message.guild.id].voiceChannel.leave()
         } else {
             setTimeout(function () {
                 playMusic(guilds[message.guild.id].queue[0], message);
             }, 100);
         }
     });
 });
示例#27
-1
 .then(connection => {
   const stream = ytdl(url, { filter: 'audioonly' });
   const dispatcher = connection.playStream(stream);
   dispatcher.on('end', () => {
     voiceChannel.leave();
   });
 });
示例#28
-1
function play_next_song() {
    if (is_queue_empty()) {
        text_channel.sendMessage("The queue is empty!");
    }

    var video_id = queue[0]["id"];
    var title = queue[0]["title"];
    var user = queue[0]["user"];

    now_playing_data["title"] = title;
    now_playing_data["user"] = user;

    if (inform_np) {
        text_channel.sendMessage('Now playing: "' + title + '" (requested by ' + user + ')');
        bot.user.setGame(title);
    }

    var audio_stream = ytdl("https://www.youtube.com/watch?v=" + video_id);
    voice_handler = voice_connection.playStream(audio_stream);

    voice_handler.once("end", reason => {
        voice_handler = null;
        bot.user.setGame();
        if (!stopped && !is_queue_empty()) {
            play_next_song();
        }
    });

    queue.splice(0, 1);
}
示例#29
-1
 setTimeout(function () {
   try {
     if (!(bot.voiceConnections[0].playing) || bot.voiceConnections[0] || playlist0.length === 0) {
       try {
         bot.voiceConnections[0].destroy()
         bot.sendMessage(msg.channel, 'Nobody has requested any new songs, destroying voice connection!')
       } catch (e) {
         console.log(e)
       }
     } else if (playlist0.length > 0) {
       var ytdl2 = YT(playlist0[1], {
         quality: 140
       })
       bot.voiceConnections[0].playRawStream(ytdl2, {volume: 0.50, stereo: true}, function (err, str) {
         if (err) {
           console.log(err)
         }
         if (str) {
           bot.sendMessage(msg.channel, 'Playing next song in queue.')
         }
       })
     } else {
       console.log('> Error! Voiceconnection[0]')
     }
   } catch (e) {
     console.log('> ERRORED! voiceConnection[0] instance has encountered an issue!')
   }
 }, 5000)
示例#30
-1
function streamify (uri, opt) {
  opt = {
    ...opt,
    videoFormat: 'mp4',
    quality: 'lowest',
    audioFormat: 'mp3',
    filter (format) {
      return format.container === opt.videoFormat && format.audioEncoding
    }
  }

  const video = ytdl(uri, opt)
  const { file, audioFormat } = opt
  const stream = file ? fs.createWriteStream(file) : new PassThrough()
  const ffmpeg = new FFmpeg(video)

  process.nextTick(() => {
    const output = ffmpeg.format(audioFormat).pipe(stream)

    ffmpeg.on('error', error => stream.emit('error', error))
    output.on('error', error => {
      video.end()
      stream.emit('error', error)
    })
  })

  stream.video = video
  stream.ffmpeg = ffmpeg

  return stream
}