public static void play_youtube_audio(string url) { YouTube youtube = YouTube.Default; Video vid = youtube.GetVideo(url); System.IO.File.WriteAllBytes(videoDownloadPath + vid.FullName, vid.GetBytes()); var inputFile = new MediaFile { Filename = videoDownloadPath + vid.FullName }; var outputFile = new MediaFile { Filename = $"{videoDownloadPath + vid.FullName}.mp3" }; using (var engine = new Engine()) { engine.GetMetadata(inputFile); engine.Convert(inputFile, outputFile); } InjectMicrophone(outputFile.Filename); //removes files when done if (System.IO.File.Exists(inputFile.Filename)) { System.IO.File.Delete(inputFile.Filename); } }
public void DownloadAction() { try { IsDownloading = true; youTube = YouTube.Default; // starting point for YouTube actions video = youTube.GetVideo(Url); // gets a Video object with info about the video using (var writer = new BinaryWriter(System.IO.File.Open(@"D:\" + video.FullName, FileMode.Create))) { var bytesLeft = video.GetBytes().Length; var array = video.GetBytes(); ProgressMax = array.Length; var bytesWritten = 0; while (bytesLeft > 0) { int chunk = Math.Min(64, bytesLeft); writer.Write(array, bytesWritten, chunk); bytesWritten += chunk; bytesLeft -= chunk; CurrentProgress = bytesWritten; } } } catch (Exception ie) { MessageBox.Show($"Exception : {ie.Message}\r\n{ie.StackTrace}"); } finally { IsDownloading = false; youTube = null; video = null; } }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker backgroundWorker = (BackgroundWorker)sender; backgroundWorker.WorkerReportsProgress = true; YouTube youtube = new YouTube(); Video video = youtube.GetVideo(urlBox.Text); string title = videoTitle.Text;//video.Title.Substring(0, video.Title.Length - 10); Byte[] videoBytes = video.GetBytes(); String filePath = @"C:\Users\Icefireburn1\Videos\"; FileStream fs = new FileStream(filePath + title + video.FileExtension, FileMode.Create, FileAccess.Write); for (int offset = 0; offset < videoBytes.Length; offset += 65536) { fs.Write(videoBytes, offset, Math.Min(65536, videoBytes.Length - offset)); float percent = ((float)offset / (float)videoBytes.Length) * 100f; backgroundWorker.ReportProgress((int)Math.Round(percent, MidpointRounding.AwayFromZero)); Thread.Sleep(1); } fs.Dispose(); //Frees file so it can be converted to FLAC if (convertMp3.Checked) { toFlacFormat(filePath + title + video.FileExtension, filePath + title + ".flac"); System.IO.File.Delete(filePath + title + video.FileExtension); } }
private void DownloadSongs(ItemModel song) { if (!IsInternetAvailable()) { return; } try { var video = YouTube.GetVideo(song.YouTubeUri); if (video == null) { song.Status = FailedYoutTubeUri; return; } song.FileName = Path.GetFileNameWithoutExtension(RemoveSpecialCharacters(video.FullName.Replace(" ", string.Empty))); File.WriteAllBytes(TempPath + "\\" + RemoveSpecialCharacters(video.FullName.Replace(" ", string.Empty)), video.GetBytes()); SetStatus(song, Status.Converting); } catch (Exception ex) { SetStatus(song, Status.Failed); #if !DEBUG new LogException(ex); #endif Debug.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); } }
private static void ProcessYouTubeVideo(YouTube youtube, string url, string videoDir, string audioDir, string ffmpegPath) { Console.WriteLine("Processing URL: " + url); var video = youtube.GetVideo(url); string videoPath = videoDir + video.FullName; string audioPath = audioDir + video.Title + ".mp3"; // Download Video if (!File.Exists(videoPath)) { Console.WriteLine("Downloading video to: " + videoPath); File.WriteAllBytes(videoPath, video.GetBytes()); Console.WriteLine("Downloaded video successful"); } else { Console.WriteLine("Video already downloaded."); } // Process Audio Extraction if (!File.Exists(audioPath)) { // FFMPEG doesn't like some file names... audioPath = audioDir + ValidateFileName(video.Title) + ".mp3"; if (!File.Exists(audioPath)) { RunAudioExtraction(ffmpegPath, videoPath, audioPath); } } else { Console.WriteLine("Audio already processed for: {0}", audioPath); } }
public void addVideo(string url) { YouTubeVideo video = youTube.GetVideo(url); Videos.Add(video); OnNotifyPropertyChanged(nameof(Videos)); }
private void DownloadVideo(VideoData videoData, string path) { YouTube youtube = YouTube.Default; Video video = youtube.GetVideo(videoData.VideoUrl); File.WriteAllBytes(path, video.GetBytes()); }
private YouTubeVideo GetYoutube(string url) { YouTube b = YouTube.Default; YouTubeVideo v = b.GetVideo(url); return(v); }
/// <summary> /// Main start of the program /// </summary> /// <param name="apikey">Key provided by the user (Shazam api key)</param> /// <param name="url">YouTube url of the song</param> private bool Start(string apikey, string url, string searchTerms = "") { EnableFields(false); YouTube youtube = YouTube.Default; video = youtube.GetVideo(url); if (searchTerms.Trim() == string.Empty) { song = getSongInfo(video.FullName, apikey); } else { song = getSongInfo(searchTerms, apikey); } if (song == null) { var status = "No song found"; var message = "Enter a valid title and/or artist to specify song."; ShowError(status, message); UpdateStatusUI("Invalid song title and/or artist.", true); return(false); } UpdateSongInfoDisplay(); UpdateStatusUI("Verify song information and press Download to continue."); EnableFields(true); return(true); }
/// <summary> /// Save YouTube video /// </summary> /// <param name="url">video YouTube url</param> /// <param name="path">absolute path of where save this video</param> /// <returns>operation completed or not</returns> bool SaveVideoOnDisk(string url, string path) { YouTube youTube = YouTube.Default; YouTubeVideo video = null; try { video = youTube.GetVideo(url); if (File.Exists(Path.Combine(path, video.FullName))) { Console.WriteLine("The file '" + Path.Combine(path, video.FullName) + "' already exists. Operation canceled."); return(false); } File.WriteAllBytes(Path.Combine(path, video.FullName), video.GetBytes()); return(true); } catch (Exception) { throw; } finally { youTube = null; video = null; } }
private void UrlTextBox_TextChanged(object sender, EventArgs e) { try { YouTubeVideo youTubeVideo = youTube.GetVideo(UrlTextBox.Text); string youTubeVideoName = youTubeVideo.Title; foreach (char c in Path.GetInvalidFileNameChars()) { youTubeVideoName = youTubeVideoName.Replace(c, '_'); } NameTextBox.Text = youTubeVideoName; } catch { NameTextBox.Text = ""; } }
public async Task Play(CommandContext ctx, [RemainingText, Description("Full youtube URL.")] string YoutubeURL) { if (!YoutubeURL.ToLower().StartsWith("http://")) { YoutubeURL = "https://" + YoutubeURL; } await TryDelete(ctx); string filename = ""; Video vid = null; try { YouTube youtube = YouTube.Default; vid = youtube.GetVideo(YoutubeURL); if (!Directory.Exists("Bot")) { Directory.CreateDirectory("Bot"); } filename = MusicBot.CreatePathFromVid(vid); if (!File.Exists(filename)) { await DiscordUtils.SendBotMessage(Messages.AudioDownloading, ctx.Message.Channel, user : ctx.User); string filenameNoMP3 = @Directory.GetCurrentDirectory() + "\\Bot\\" + vid.FullName + ".Temp"; File.WriteAllBytes(filenameNoMP3, vid.GetBytes()); var inputFile = new MediaFile { Filename = filenameNoMP3 }; var outputFile = new MediaFile { Filename = filename }; using (var engine = new Engine()) { engine.GetMetadata(inputFile); engine.Convert(inputFile, outputFile); } File.Delete(filenameNoMP3); } } catch (Exception e) { await ctx.RespondAsync("Error: " + e.Message); await Task.Delay(1); return; } if (vid != null) { MusicBot.AddToQueue(vid); } await DiscordUtils.SendBotMessage(Utils.Replace(Messages.AudioMusicAddedToQueue, "~1", vid.Title), ctx.Message.Channel, user : ctx.User); await MusicBot.Play(ctx); }
private void urlBox_TextChanged(object sender, EventArgs e) { if (urlBox.Text.Contains("youtube.com/")) { YouTube youtube = new YouTube(); Video video = youtube.GetVideo(urlBox.Text); videoTitle.Text = video.Title.Substring(0, video.Title.Length - 10); } }
private void downloadMethod(object url) { string urlString = (string)url; YouTube youTube = new YouTube(); YouTubeVideo video = youTube.GetVideo(urlString); File.WriteAllBytes(@"C:\Users\Daix wap\" + video.FullName, video.GetBytes()); }
public async Task Play([Remainder, Summary("youtube url")] string strUrl) { var guildId = (null == Context.Guild ? Context.Channel.Id : Context.Guild.Id); if (StateCache.Guilds[guildId].bSongPlaying) { if (!StateCache.Guilds[guildId].queueSongs.Contains(strUrl)) { StateCache.Guilds[guildId].queueSongs.Enqueue(strUrl); await Context.Channel.SendMessageAsync("Song added to queue..."); await HandleQueue(guildId); } else { await Context.Channel.SendMessageAsync("Song already in queue"); } return; } // Get the audio channel IVoiceChannel channel = (Context.Message.Author as IGuildUser).VoiceChannel; if (channel == null) { await Context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument."); return; } try { if (!directory.Exists) { directory.Create(); } StateCache.Guilds[guildId].bSongPlaying = true; StateCache.Guilds[guildId].audioClient = await channel.ConnectAsync(); YouTube youtube = YouTube.Default; Video vid = youtube.GetVideo(strUrl); await Context.Channel.SendMessageAsync(string.Format("Playing {0}...", vid.Title)); File.WriteAllBytes(@"C:\tmp\" + vid.FullName.Replace(" ", ""), vid.GetBytes()); string strFilePath = @"C:\tmp\" + vid.FullName.Replace(" ", "") + ".mp3"; var inputFile = new MediaFile(@"C:\tmp\" + vid.FullName.Replace(" ", "")); var outputFile = new MediaFile(strFilePath); using (var engine = new Engine()) { engine.GetMetadata(inputFile); engine.Convert(inputFile, outputFile); } await SendAsync(StateCache.Guilds[guildId].audioClient, strFilePath, guildId); } catch (Exception ex) { } }
// returns path where the video has been downloaded to private string DownloadVideo(string url) { YouTube youTube = YouTube.Default; var video = youTube.GetVideo(url); string filename = string.Join("", video.Title.Split(Path.GetInvalidFileNameChars())); File.WriteAllBytes(Path.GetFullPath(tempPath + filename + video.FileExtension), video.GetBytes()); return(Path.GetFullPath(@"temp\" + filename + video.FileExtension)); }
public string YTDownload(string url) { var video = youTube.GetVideo(url); string fullName = video.FullName; byte[] vidByte = video.GetBytes(); File.WriteAllBytes(MediaFolder + fullName, vidByte); return(MediaFolder + fullName); }
public SongInQueue DownloadSong(string link) { try { _log.Info("Started processing file " + link); string guid = Guid.NewGuid().ToString(); SongInQueue result = new SongInQueue(); YouTube youtube = YouTube.Default; string fullFilePath = _musicStorage + guid; Video vid = youtube.GetVideo(link); _log.Info("Finished downloading file " + link); result.Name = GetPropperName(vid); File.WriteAllBytes(fullFilePath, vid.GetBytes()); _log.Info("Finished saving file to the disc."); var inputFile = new MediaFile(fullFilePath); var fullFilePathWithExtension = $"{fullFilePath}.mp3"; var outputFile = new MediaFile(fullFilePathWithExtension); result.FilePath = fullFilePathWithExtension; var convertSW = new Stopwatch(); using (Engine convertEngine = new Engine()) { convertEngine.GetMetadata(inputFile); convertSW.Start(); convertEngine.Convert(inputFile, outputFile); convertSW.Stop(); } _log.Info($"Finished convering. Time: { convertSW.Elapsed.ToString() }"); if (File.Exists(fullFilePath)) { File.Delete(fullFilePath); } else { throw new NotImplementedException(); } _log.Info("Finished processing file " + link); return(result); } catch (Exception ex) { _log.Info($"Failed to prepare file: { ex }"); } return(null); }
// Downloads youtube video and adds it to the queue public async Task Download(string Url, CommandEventArgs e) { YouTube _tubeClient = YouTube.Default; YouTubeVideo Video = _tubeClient.GetVideo(Url); string title = Video.Title; string fullName = Video.FullName; byte[] bytes = Video.GetBytes(); await AddItem(fullName.Replace(' ', '_'), bytes, e, title); }
public static bool YoutubePathExists(string path) { try { YouTube youtube = new YouTube(); var vid = youtube.GetVideo(path); return(true); } catch { return(false); } }
/* * Write File * @return the name of the mp3 file */ public Sound Download(string url) { _video = _youTube.GetVideo(url); WriteFileAsync(_video); _mp3FileName = _video.FullName.Substring(0, _video.FullName.Length - 14); var sound = new Sound(_mp3FileName, _mp3FileName + ".mp3"); sound.VideoName = _video.FullName; return(sound); }
//Este método descarga el vídeo en base a un link, le pasamos también el contexto para poder enviar los mensajes a la conversación public string DescargarVideo(String link, String calidad, Boolean musica) { try { context.PostAsync(Dialogos.MensajeAleatorio(Dialogos.msg_Descargando)); //Llamamos a la clase YouTube YouTube youTube = YouTube.Default; //Obtenemos el objeto del Video YouTubeVideo video = youTube.GetVideo(link); //Generamos la ruta de descarga (video.FullName incluye .mp4) String strFileDestination = (System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + @"temp\" + video.FullName).Replace(" ", ""); //Si el vídeo no existe en el directorio esribimos el archivo con los Bytes del video if (!File.Exists(strFileDestination)) { //Escribimos el archivo con los bytes del video File.WriteAllBytes(strFileDestination, video.GetBytes()); } if (musica) { //Si no existe el archivo .mp3 if (!File.Exists($"{strFileDestination}.mp3")) { //Variable con la ruta del ejecutable de ffmpeg.exe String ffmpegExe = (System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + @"bin\ffmpeg.exe"); //Este método se encarga de la conversión a mp3 Execute(ffmpegExe, String.Format("-i {0} -f mp3 -ab {1} -vn {2}", strFileDestination, calidad, strFileDestination + ".mp3")); //Eliminamos el archivo .mp4 File.Delete(strFileDestination); } //Devolvemos la ruta del enlace return((video.FullName + ".mp3").Replace(" ", "")); } else { //Devolvemos la ruta del enlace return((video.FullName).Replace(" ", "")); } } catch { //En caso de error devolvemos un mensaje return(Dialogos.msg_ErrorDescargaAudio); } }
private YouTubeVideo GetYoutubeVideo(string url) { YouTube youTube = YouTube.Default; YouTubeVideo video; try { video = youTube.GetVideo(url); } catch (InvalidOperationException) { return(null); } return(video); }
public YouTubeVideo GetYouTubeVideo(string videoURL) { // try create an instance of the YouTube video with the specified url try { YouTube youtube = YouTube.Default; YouTubeVideo video = youtube.GetVideo(videoURL); return(video); } // video does not exist catch (Exception) { return(null); } }
private void DownloadYoutubeVideo(string youtubeVideoUrl, string saveToFolder = null) { display("Downloading Video please wait ... "); var localFolder = @saveToFolder ?? destFolder; YouTube youtube = YouTube.Default; Video vid = youtube.GetVideo(youtubeVideoUrl); var localFilename = localFolder + vid.FullName; System.IO.File.WriteAllBytes(localFilename, vid.GetBytes()); display($" Video Download Completed: {localFilename}"); txtMessages.BackColor = Color.White; }
public void GetYoutubeAudioFile(InputField link) { ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; string source = Directory.GetCurrentDirectory(); try { YouTube youtube = YouTube.Default; FFMPEG ffmpeg = new FFMPEG(Path.Combine(Application.dataPath, @"StreamingAssets\youtube-dl\ffmpeg.exe")); YouTubeVideo vid = youtube.GetVideo(link.text); string path = source + @"\" + RemoveIllegalPathCharacters(vid.Title.Replace(" - YouTube", "")) + vid.FileExtension; if (File.Exists(path)) { try { File.Delete(path); } catch (Exception ex) { Debug.LogError(ex); } } File.WriteAllBytes(path, vid.GetBytes()); string wavPath = path.Replace(vid.FileExtension, ".wav"); string result = ffmpeg.RunCommand("-i \"" + path + "\" -acodec pcm_u8 -ar 22050 \"" + wavPath + "\""); if (File.Exists(path)) { try { File.Delete(path); } catch (Exception ex) { Debug.LogError(ex); } } videoTitleText.text = Path.GetFileNameWithoutExtension(wavPath); audioPath = wavPath; } catch (Exception ex) { Debug.LogError(ex); videoTitleText.text = "<color=red>" + ex.ToString() + "</color>"; link.text = ""; } }
public void DownloadYoutube(string youtubeUrl, string pathToyoutubeVideo) { thread = new Thread(() => { YouTube youtube = YouTube.Default; Video vid = youtube.GetVideo(youtubeUrl); string file = pathToyoutubeVideo + vid.FullName; File.WriteAllBytes(file, vid.GetBytes()); Console.WriteLine(pathToyoutubeVideo + vid.FullName); }); thread.Start(); Wait(); }
private void button1_Click(object sender, EventArgs e) { YouTube youtube = YouTube.Default; Video vid = youtube.GetVideo(textBox1.Text); label2.Text = vid.FullName; File.WriteAllBytes(Application.StartupPath + @"\mp3\" + vid.FullName, vid.GetBytes()); var inputfile = new MediaFile { Filename = $"{Application.StartupPath + @"\mp3\" + vid.FullName}" }; var outputfile = new MediaFile { Filename = $"{Application.StartupPath + @"\mp3\" + vid.FullName}.mp3" }; if (true) { using (var engine = new Engine()) { engine.GetMetadata(inputfile); engine.Convert(inputfile, outputfile); } MessageBox.Show("İndirme tamamlandı ! ", "Youtube İndirme "); label2.Text = ""; textBox1.Text = ""; if (chMP3.Checked == true) {//delete mp4 for mp3 File.Delete(Application.StartupPath + @"\mp3\" + vid.FullName); } else if (chMP4.Checked == true) {//delete mp3 for mp4 File.Delete(Application.StartupPath + @"\mp3\" + vid.FullName + ".mp3"); } //mp3 u silip sadece mp4 u geride bırakıyor //izlediğiniz için tşk :D } else { MessageBox.Show("İndirme tamamlanamadı !", "Youtube İndirme "); } // Hem video hem mp3 indiriyor sadece mp3 indirmesini istersek mp4 dosyayı silicez // veya tam tersi mp3 u silip video dosyasına erişebiliriz }
public void Download(string url) { YouTubeVideo video; if (_downloadFolder.Equals("none")) { MessageBox.Show("Set a download folder!"); return; } try { video = _youtube.GetVideo(url); } catch { MessageBox.Show("Invalid URL"); return; } if (video == null) { return; } File.WriteAllBytes(Path.Combine(_videosFolder, video.FullName), video.GetBytes()); var inputFile = new MediaFile { Filename = Path.Combine(_videosFolder, video.FullName) }; var outputFile = new MediaFile { Filename = Path.Combine(_downloadFolder, $"{video.FullName}.mp3") }; using (var engine = new Engine()) { engine.GetMetadata(inputFile); engine.Convert(inputFile, outputFile); } File.Delete(Path.Combine(_videosFolder, video.FullName)); MessageBox.Show("Done!"); }
// extra data 1: // extra data 2: // extra data 3: public override void HotkeyTriggered() { MainLogic.Instance.InputCallbacks.TextResultRequestCallback("YouTube Video Link", (bool ytCancelled, string ytInput) => { if (!ytCancelled) { MainLogic.Instance.InputCallbacks.FileSaveRequestCallback("MP3 File (*.mp3)|*.mp3", "Converted File Location", (bool fileLocCancelled, string saveFileLoc) => { if (!fileLocCancelled) { MainLogic.Instance.InputCallbacks.TextResultRequestCallback("Start Time (HH:mm:ss) (leave blank or 0 for beginning)", (bool stCancelled, string startTime) => { if (!stCancelled) { MainLogic.Instance.InputCallbacks.TextResultRequestCallback("Duration Time (HH:mm:ss) (leave blank or 0 for full)", (bool durTimeCancelled, string durTime) => { if (!durTimeCancelled) { string youtubeLink = ytInput; string saveFileLink = saveFileLoc; string seekTime = startTime; string durationTime = durTime; YouTube youTube = YouTube.Default; YouTubeVideo video = youTube.GetVideo(youtubeLink); string saveVideoLink = TempFileDirectory + @"\" + video.FullName; File.WriteAllBytes(TempFileDirectory + @"\" + video.FullName, video.GetBytes()); Convert(saveVideoLink, saveFileLink, seekTime, durationTime); if (File.Exists(saveVideoLink)) { File.Delete(saveVideoLink); } MainLogic.Instance.InputCallbacks.DisplayInfoRequestCallback("Finished."); } }); } }); } }); } }); }