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 bgwVideo_DoWork(object sender, DoWorkEventArgs e) { try { var backgroundWorker = sender as BackgroundWorker; bgwVideo.ReportProgress(20); var youTube = YouTube.Default; bgwVideo.ReportProgress(20); YouTubeVideo video = youTube.GetVideo(this.txtLink.Text); this.videoTitle = video.Title; File.WriteAllBytes(Path.Combine(folderName, video.FullName), video.GetBytes()); bgwVideo.ReportProgress(40); File.WriteAllBytes(Path.Combine(folderName, video.FullName), video.GetBytes()); bgwVideo.ReportProgress(20); if (bgwVideo.CancellationPending) { e.Cancel = true; } } catch (Exception ex) { this.Invoke((Func <DialogResult>)(() => MessageBox.Show(this, "No se puede descargar el vídeo.\nCompruebe el enlace."))); } }
public void saveVideo(YouTubeVideo video) { string folder = GetCustomExportFolder(); string path = Path.Combine(folder, video.FullName); File.WriteAllBytes(path, video.GetBytes()); }
public void saveAudio(YouTubeVideo video) { string folder; folder = GetCustomExportFolder(); string path = Path.Combine(folder, video.FullName); File.WriteAllBytes(path, video.GetBytes()); var inputFile = new MediaFile { Filename = path }; var outputFile = new MediaFile { Filename = path.Replace(".mp4", "") + ".mp3" }; using (var engine = new Engine()) { engine.Convert(inputFile, outputFile); } if (File.Exists(path)) { File.Delete(path); } }
public Core.Classes.Video GetVideoByUrl(Uri uri) { var youtube = YouTube.Default; YouTubeVideo ytVideo = youtube.GetVideo(uri.AbsoluteUri); var filePath = $@"{GetHashString(uri.ToString())}.mp4"; byte[] bytes = null; if (!File.Exists(filePath)) { bytes = ytVideo.GetBytes(); File.WriteAllBytes(filePath, bytes); } else { bytes = File.ReadAllBytes(filePath); } return(new Core.Classes.Video( ytVideo.Title, ytVideo.Uri, (Core.Classes.VideoFormat)ytVideo.Format, (Core.Classes.AudioFormat)ytVideo.AudioFormat, bytes, filePath )); }
/// <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 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()); }
// 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); }
/* * Method for writing the video and audio files */ private async void WriteFileAsync(YouTubeVideo video) { StorageFile mp4StorageFile = await _storageFolder.CreateFileAsync(video.FullName, CreationCollisionOption.ReplaceExisting); // Store the video as a MP4 await FileIO.WriteBytesAsync(mp4StorageFile, video.GetBytes()); _mp3FileName = mp4StorageFile.Name.Substring(0, mp4StorageFile.Name.Length - 14); StorageFile mp3StorageFile = await _storageFolder.CreateFileAsync(_mp3FileName + ".mp3", CreationCollisionOption.ReplaceExisting); var profile = MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High); await ToAudioAsync(mp4StorageFile, mp3StorageFile, profile); }
//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 IEnumerator SaveVideoToDisk(string link) { var youTube = YouTube.Default; // starting point for YouTube actions _video = youTube.GetVideo(link); // gets a Video object with info about the video _videoPath = Path.Combine(Application.streamingAssetsPath, "video.mp4"); print($"_videoPath: {_videoPath}"); //File.WriteAllBytes(_videoPath, _video.GetBytes()); print("start"); yield return(AssetBundle.LoadFromMemoryAsync(_video.GetBytes())); print("end"); //var clip = Resources.Load("video") as VideoClip; }
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 bool SaveMP3(string source, YouTubeVideo video, string soundName) { string fileName = source + soundName + ".mp4"; File.WriteAllBytes(fileName, video.GetBytes()); try { File.Move(fileName, Path.ChangeExtension(fileName, ".mp3")); } catch (IOException) { File.Delete(Path.Combine(source, fileName)); return(false); } return(true); }
protected void Download(List <string> idList, string channelTitle) { int videosCount = idList.Count; int num = 1; Console.WriteLine($"Количество видео для скачивания: {videosCount}"); foreach (var id in idList) { YouTubeVideo video = _service.GetVideo("https://youtube.com/watch?v=" + id); Console.WriteLine($"{num++} {video.FullName}. Id = {id}"); var folder = GetDefaultFolder(channelTitle); string path = Path.Combine(folder, video.FullName); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } File.WriteAllBytes(path, video.GetBytes()); } }
/// <summary> /// Downloads the song once the information is verified /// </summary> private string DownloadSong() { string filePath = string.Empty; if (song == null || targetDir == null || video == null) { UpdateStatusUI("Song info error", true); } try { UpdateStatusUI("Downloading song " + song.Title + "..."); filePath = Downloader.Download(video.GetBytes(), song.Title, "mp4"); } catch (Exception error) { string status = "Failed to download song"; UpdateStatusUI(status, true); ShowError(status, error.Message.ToString()); } return(filePath); }
private void DownloadAndConvert(string format) { try { Invoke(new Action <bool>(SetEnabled), false); YouTubeVideo youTubeVideo = youTube.GetVideo(UrlTextBox.Text); string youTubeVideoName = String.IsNullOrWhiteSpace(NameTextBox.Text) ? youTubeVideo.Title : NameTextBox.Text; foreach (char c in Path.GetInvalidFileNameChars()) { youTubeVideoName = youTubeVideoName.Replace(c, '_'); } File.WriteAllBytes(musicPlayer.cachePath + youTubeVideoName + youTubeVideo.FileExtension, youTubeVideo.GetBytes()); MediaFile inputFile = new MediaFile { Filename = musicPlayer.cachePath + youTubeVideoName + youTubeVideo.FileExtension }; MediaFile outputFile = new MediaFile { Filename = $"{directoryInfo.FullName + "\\" + youTubeVideoName + format}" }; using (Engine engine = new Engine()) { engine.GetMetadata(inputFile); engine.Convert(inputFile, outputFile); } if (File.Exists(inputFile.Filename)) { File.Delete(inputFile.Filename); } Invoke(new Action(ReloadTreeBranch)); Invoke(new Action <string, string>(ShowMessage), "YouTube Converter Info:", "Your video was successfully converted!"); Invoke(new Action(Close)); } catch (Exception ex) { ex.ToString(); Invoke(new Action <bool>(SetEnabled), true); Invoke(new Action <string, string>(ShowMessage), "YouTube-Converter Error:", "Conversion of video failed!"); } }
private void DownloadAudio(YouTubeVideo video, RadioChannel radio, string url, string title) { File.WriteAllBytes("Saves/Radio/" + radio.m_guildId + "/" + title + "." + video.FileExtension, video.GetBytes()); MediaFile inputFile = new MediaFile { Filename = "Saves/Radio/" + radio.m_guildId + "/" + title + "." + video.FileExtension }; MediaFile outputFile = new MediaFile { Filename = "Saves/Radio/" + radio.m_guildId + "/" + title + ".mp3" }; using (Engine engine = new Engine()) { engine.Convert(inputFile, outputFile); } radio.StopDownloading(url); File.Delete("Saves/Radio/" + radio.m_guildId + "/" + title + "." + video.FileExtension); radio.Play(); }
// 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."); } }); } }); } }); } }); }
public byte[] GetBytes() { return(_youTubeVideo.GetBytes()); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs evt) { try { YouTube youtube = YouTube.Default; var backgroundWorker = sender as BackgroundWorker; backgroundWorker1.ReportProgress(10); if (betterAudioQualityToolStripMenuItem.Checked) { var vid = youtube.GetAllVideos(this.txtLink.Text); var audio = vid .Where(e => e.AudioFormat == AudioFormat.Aac && e.AdaptiveKind == AdaptiveKind.Audio) .ToList(); this.videoTitle = audio[0].Title; if (audio.Count > 0) { backgroundWorker1.ReportProgress(10); System.IO.File.WriteAllBytes(Path.Combine(folderName, audio[0].FullName), audio[0].GetBytes()); backgroundWorker1.ReportProgress(30); var inputFile = new MediaFile { Filename = Path.Combine(folderName, audio[0].FullName) }; var outputFile = new MediaFile { Filename = $"{Path.Combine(folderName, audio[0].FullName)}.mp3" }; backgroundWorker1.ReportProgress(20); using (var engine = new Engine()) { backgroundWorker1.ReportProgress(10); engine.Convert(inputFile, outputFile); backgroundWorker1.ReportProgress(10); } File.Delete(Path.Combine(folderName, audio[0].FullName)); backgroundWorker1.ReportProgress(10); } } else { YouTubeVideo audio = youtube.GetVideo(this.txtLink.Text); this.videoTitle = audio.Title; backgroundWorker1.ReportProgress(10); File.WriteAllBytes(Path.Combine(folderName, audio.FullName), audio.GetBytes()); backgroundWorker1.ReportProgress(30); var inputFile = new MediaFile { Filename = Path.Combine(folderName, audio.FullName) }; var outputFile = new MediaFile { Filename = $"{Path.Combine(folderName, audio.FullName)}.mp3" }; backgroundWorker1.ReportProgress(20); using (var engine = new Engine()) { backgroundWorker1.ReportProgress(10); engine.Convert(inputFile, outputFile); backgroundWorker1.ReportProgress(10); } File.Delete(Path.Combine(folderName, audio.FullName)); backgroundWorker1.ReportProgress(10); } if (backgroundWorker1.CancellationPending) { evt.Cancel = true; } } catch (ThreadAbortException ex) { } catch (Exception e) { this.Invoke((Func <DialogResult>)(() => MessageBox.Show(this, "No se puede descargar el vídeo.\nCompruebe el enlace."))); } }