public string Convert() { string smessage = string.Empty; if (string.IsNullOrEmpty(FilePath) || string.IsNullOrEmpty(OutPutFilePath) || string.IsNullOrEmpty(FileFormat)) { smessage = "Input path,Output path and file format are maindatory."; } else { try { var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); switch (FileFormat) { case Format.webm: ffMpeg.ConvertMedia(FilePath, OutPutFilePath, Format.webm); break; case Format.mp4: ffMpeg.ConvertMedia(FilePath, OutPutFilePath, Format.mp4); break; case Format.mov: ffMpeg.ConvertMedia(FilePath, OutPutFilePath, Format.mov); break; } } catch (Exception ex) { throw new Exception("Unable to convert. " + ex.Message); } } return(smessage); }
//media converter...... private void button14_Click_1(object sender, EventArgs e) { hideSubMenu(); //hides playlist panel. playlistPanel.Visible = false; MediaItems.Visible = false; try { OpenFileDialog ofd = new OpenFileDialog(); if (ofd.ShowDialog() == DialogResult.OK) { OpenDisplay(new Converting()); try { var convert = new NReco.VideoConverter.FFMpegConverter(); convert.ConvertMedia(ofd.FileName, @"C:\Users\Olanrewaju\Desktop\Converted.mp4", NReco.VideoConverter.Format.mp4); } catch (Exception ex) { MessageBox.Show("Error: " + ex); } MessageBox.Show("Convert complete"); } } catch (Exception ex) { MessageBox.Show("Error: " + ex); } }
private List <string> GetVideoFile() { var ret = new List <string>(); try { foreach (string fl in Request.Files) { if (fl != null && Request.Files[fl].ContentLength > 0) { var allvtype = "mp4,mp3,h264,wmv,wav,avi,flv,mov,mkv,webm,ogg"; var ext = Path.GetExtension(Request.Files[fl].FileName).ToLower().Replace(".", "").Trim(); if (allvtype.Contains(ext)) { string datestring = DateTime.Now.ToString("yyyyMMdd"); string imgdir = Server.MapPath("~/userfiles") + "\\docs\\" + datestring + "\\"; if (!Directory.Exists(imgdir)) { Directory.CreateDirectory(imgdir); } var fn = Path.GetFileName(Request.Files[fl].FileName) .Replace(" ", "_").Replace("#", "") .Replace("&", "").Replace("?", "").Replace("%", "").Replace("+", ""); fn = Path.GetFileNameWithoutExtension(fn) + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetExtension(fn); var onlyname = Path.GetFileNameWithoutExtension(fn); var srcvfile = imgdir + fn; //store file to local Request.Files[fl].SaveAs(srcvfile); var imgname = onlyname + ".jpg"; var imgpath = imgdir + imgname; var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); ffMpeg.GetVideoThumbnail(srcvfile, imgpath); var oggname = onlyname + ".ogg"; var oggpath = imgdir + oggname; var ffMpeg1 = new NReco.VideoConverter.FFMpegConverter(); ffMpeg1.ConvertMedia(srcvfile, oggpath, NReco.VideoConverter.Format.ogg); if (!ext.Contains("mp4")) { var mp4name = onlyname + ".mp4"; var mp4path = imgdir + mp4name; var ffMpeg2 = new NReco.VideoConverter.FFMpegConverter(); ffMpeg2.ConvertMedia(srcvfile, mp4path, NReco.VideoConverter.Format.mp4); } var url = "/userfiles/docs/" + datestring + "/" + onlyname; ret.Add(url); } //end if ext } //file is not null } //foreach } catch (Exception ex) { ret.Clear(); } return(ret); }
private void button2_Click(object sender, EventArgs e) { var videoConv = new NReco.VideoConverter.FFMpegConverter(); videoConv.ConvertMedia(giris, cikis + ".mp3", "mp3"); File.Delete(giris); }
//el async permite que sea un proceso asincrono, es decir que el proceso de conversión siga corriendo //independientemente de los demás procesos, y que no parezca que el programa se congeló private async void button1_ClickAsync(object sender, EventArgs e) { //nuevo cliente de Youtube var client = new YoutubeClient(); //lee la dirección de youtube que le escribimos en el textbox var videoId = NormalizeVideoId(txtURL.Text); var video = await client.GetVideoAsync(videoId); var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId); // Busca la mejor resolución en la que está disponible el video var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality(); // Compone el nombre que tendrá el video en base a su título y extensión var fileExtension = streamInfo.Container.GetFileExtension(); var fileName = $"{video.Title}.{fileExtension}"; //TODO: Reemplazar los caractéres ilegales del nombre //fileName = RemoveIllegalFileNameChars(fileName); //Activa el timer para que el proceso funcione de forma asincrona tmrVideo.Enabled = true; // mensajes indicando que el video se está descargando txtMensaje.Text = "Descargando el video ... "; //TODO: se pude usar una barra de progreso para ver el avance //using (var progress = new ProgressBar()) //Empieza la descarga await client.DownloadMediaStreamAsync(streamInfo, fileName); //Ya descargado se inicia la conversión a MP3 var Convert = new NReco.VideoConverter.FFMpegConverter(); //Especificar la carpeta donde se van a guardar los archivos, recordar la \ del final String SaveMP3File = @"E:\MP3\" + fileName.Replace(".mp4", ".mp3"); //Guarda el archivo convertido en la ubicación indicada Convert.ConvertMedia(fileName, SaveMP3File, "mp3"); //Si el checkbox de solo audio está chequeado, borrar el mp4 despues de la conversión if (ckbAudio.Checked) { File.Delete(fileName); } //Indicar que se terminó la conversion txtMensaje.Text = "Archivo Convertido en MP3"; tmrVideo.Enabled = false; txtMensaje.BackColor = Color.White; //TODO: Cargar el MP3 al reproductor o a la lista de reproducción //CargarMP3s(); //Se puede incluir un checkbox para indicar que de una vez se reproduzca el MP3 //if (ckbAutoPlay.Checked) // ReproducirMP3(SaveMP3File); return; }
public JsonResult UploadWebmVideoData() { foreach (string fl in Request.Files) { if (fl != null && Request.Files[fl].ContentLength > 0) { string datestring = DateTime.Now.ToString("yyyyMMdd"); string imgdir = Server.MapPath("~/userfiles") + "\\docs\\" + datestring + "\\"; if (!Directory.Exists(imgdir)) { Directory.CreateDirectory(imgdir); } var fn = "V" + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".webm"; var onlyname = Path.GetFileNameWithoutExtension(fn); var srcvfile = imgdir + fn; Request.Files[fl].SaveAs(srcvfile); //var imgname = onlyname + ".jpg"; //var imgpath = imgdir + imgname; //var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); //ffMpeg.GetVideoThumbnail(srcvfile, imgpath); //var oggname = onlyname + ".ogg"; //var oggpath = imgdir + oggname; //var ffMpeg1 = new NReco.VideoConverter.FFMpegConverter(); //ffMpeg1.ConvertMedia(srcvfile, oggpath, NReco.VideoConverter.Format.ogg); var mp4name = onlyname + ".mp4"; var mp4path = imgdir + mp4name; var ffMpeg2 = new NReco.VideoConverter.FFMpegConverter(); var setting = new NReco.VideoConverter.ConvertSettings(); setting.VideoFrameRate = 30; setting.AudioSampleRate = 44100; ffMpeg2.ConvertMedia(srcvfile, NReco.VideoConverter.Format.webm, mp4path, NReco.VideoConverter.Format.mp4, setting); try { System.IO.File.Delete(srcvfile); } catch (Exception ex) { } var url = "/userfiles/docs/" + datestring + "/" + mp4name; var videohtml = "<p><video width='640' height='480' controls src='" + url + "' type='video/mp4'>" + "Your browser does not support the video tag. </video></p>"; var ret1 = new JsonResult(); ret1.Data = new { data = videohtml }; return(ret1); } } var ret = new JsonResult(); ret.Data = new { data = "<p></p>" }; return(ret); }
private AudioTrack(string videoFilePath) { var converter = new NReco.VideoConverter.FFMpegConverter(); var fileInfo = new FileInfo(videoFilePath); var directory = fileInfo.Directory.FullName; var fileName = fileInfo.Name; var audioFilePath = Path.Combine(directory, fileName.Replace(".mp4", ".mp3")); converter.ConvertMedia(videoFilePath, audioFilePath, "mp3"); this.AudioFilePath = audioFilePath; }
private void buttonConvert_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(inputVideo)) { var convertVideo = new NReco.VideoConverter.FFMpegConverter(); convertVideo.ConvertMedia(inputVideo, outputFile + ".mp3", "mp3"); MessageBox.Show("converted!!"); } else { MessageBox.Show("choose video"); } }
private void buttonConvert_Click(object sender, EventArgs e) { if ((pathAudio.Text == string.Empty && pathVideo.Text == string.Empty) || pathAudio.Text == string.Empty || pathVideo.Text == string.Empty) { MessageBox.Show("You have to select both options!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { var convert = new NReco.VideoConverter.FFMpegConverter(); convert.ConvertMedia(pathVideo.Text.Trim(), pathAudio.Text.Trim(), "mp3"); MessageBox.Show("Done.", "Convert", MessageBoxButtons.OK); } }
private static void ConvertVideoFromQueue(string inputPath) { ProgramIsBusy = true; ProcessQueue.Dequeue(); //Pick up file paths of files that are created in WatchingPath directory then pass them into converter. var fileConverter = new NReco.VideoConverter.FFMpegConverter(); //Parse inputPath and Create a directory in the OutputPath for the file. var filePath = inputPath.Split('\\').Last(); var outputPath = string.Format(@"{0}\{1}", ConfigurationSettings.AppSettings["OutputPath"], filePath); fileConverter.ConvertMedia(inputPath, outputPath, "mp4"); ProgramIsBusy = false; }
public string RetrieveUploadVideo() { var ret = ""; try { foreach (string fl in Request.Files) { if (fl != null && Request.Files[fl].ContentLength > 0) { string fn = Path.GetFileName(Request.Files[fl].FileName) .Replace(" ", "_").Replace("#", "") .Replace("&", "").Replace("?", "").Replace("%", "").Replace("+", ""); var ext = Path.GetExtension(fn).ToLower(); var allvtype = ".mp4,.mp3,.h264,.wmv,.wav,.avi,.flv,.mov,.mkv,.webm,.ogg,.mov,.mpg"; if (allvtype.Contains(ext)) { string datestring = DateTime.Now.ToString("yyyyMMdd"); string imgdir = Server.MapPath("~/userfiles") + "\\docs\\" + datestring + "\\"; if (!Directory.Exists(imgdir)) { Directory.CreateDirectory(imgdir); } var srvfd = Path.GetFileNameWithoutExtension(fn) + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetExtension(fn); Request.Files[fl].SaveAs(imgdir + srvfd); if (!ext.Contains("mp4")) { var mp4name = Path.GetFileNameWithoutExtension(srvfd) + ".mp4"; var mp4path = imgdir + mp4name; var ffMpeg2 = new NReco.VideoConverter.FFMpegConverter(); ffMpeg2.ConvertMedia(imgdir + srvfd, mp4path, NReco.VideoConverter.Format.mp4); try { System.IO.File.Delete(imgdir + srvfd); } catch (Exception ex) { } return("/userfiles/docs/" + datestring + "/" + mp4name); } return("/userfiles/docs/" + datestring + "/" + srvfd); } //end if } //end if } } catch (Exception ex) { } return(ret); }
private static void Converter() { // gets teh video title and extension from global and assigns inputfile inputFile = video.Title + video.VideoExtension; // assigns outputfile name and extension outputFile = video.Title; // converter class instance var converter = new NReco.VideoConverter.FFMpegConverter(); // pass input and output file names together with output extension converter.ConvertMedia(inputFile, outputFile + ".mp3", "mp3"); // prints success message and makes beep sound Console.WriteLine("Successfully Converted!"); Console.Beep(); }
public void UpdateFiles() { MediaList.Clear(); foreach (var filePath in Directory.GetFiles(SourcePath).Where(item => !item.Contains(".ini"))) { var fileName = filePath.Split('\\').LastOrDefault(); var extension = filePath.Split('.').LastOrDefault(); if (SupportedVideoExtensions.Contains(extension)) { var tempFolder = Path.GetTempPath(); var tempThumbnailPath = string.Format("{0}{1}.jpg", tempFolder, fileName); var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); CreateThumbnailForVideo(filePath, tempThumbnailPath, ffMpeg); ffMpeg.Stop(); if (extension.Contains("webm")) { var newFilePath = string.Format("{0}{1}.mp4", tempFolder, fileName); if (!File.Exists(newFilePath)) { var tempffMpeg = new NReco.VideoConverter.FFMpegConverter(); tempffMpeg.ConvertMedia(filePath, newFilePath, "mp4"); tempffMpeg.Stop(); } AddMediaToList(extension, tempThumbnailPath, newFilePath); } else { AddMediaToList(extension, tempThumbnailPath, filePath); } } else { AddMediaToList(extension, filePath, filePath); } } }
private string ConvertToOpus(string inputFile, string BitRate) { string outputFile = Path.Combine(Server.MapPath("~/TempUpload"), Path.GetFileNameWithoutExtension(inputFile) + ".opus"); var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); ffMpeg.ConvertMedia(inputFile, null, // autodetect by input file extension outputFile, null, // autodetect by output file extension new NReco.VideoConverter.ConvertSettings() { CustomOutputArgs = " -acodec libopus -b:a " + BitRate + " -vbr on -compression_level 10 " } ); return(outputFile); }
private void BtnConvert_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrWhiteSpace((string)lblFilePath.Content)) { System.Windows.Forms.MessageBox.Show("You must select a file to convert."); } else if (string.IsNullOrWhiteSpace((string)lblSavePath.Content)) { System.Windows.Forms.MessageBox.Show("You must select a location to save."); } else { var convert = new NReco.VideoConverter.FFMpegConverter(); convert.ConvertMedia(mp4Path, mp3Path, "mp3"); ResetWindow(); } }
private async void DownloadYoutubeAudioOnly(string youtubeVideoUrl, string saveToFolder = null) { var mp3FolderPath = @saveToFolder ?? destFolder; // Client var client = new YoutubeClient(); var videoId = NormalizeVideoId(youtubeVideoUrl); var video = await client.GetVideoAsync(videoId); var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId); // Get the best muxed stream var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality(); // Compose file name, based on metadata var fileExtension = streamInfo.Container.GetFileExtension(); var fileName = $"{video.Title}.{fileExtension}"; // Replace illegal characters in file name fileName = RemoveInvalidChars(fileName); //RemoveIllegalFileNameChars(fileName); timerVideo.Enabled = true; // Download video txtMessages.Text = "Downloading Video please wait ... "; //using (var progress = new ProgressBar()) await client.DownloadMediaStreamAsync(streamInfo, fileName); // Add Nuget package: https://www.nuget.org/packages/NReco.VideoConverter/ To Convert MP4 to MP3 if (chkAudioOnly.Checked) { var Convert = new NReco.VideoConverter.FFMpegConverter(); string saveMp3File = mp3FolderPath + fileName.Replace(".mp4", ".mp3"); Convert.ConvertMedia(fileName, saveMp3File, "mp3"); //Delete the MP4 file after conversion File.Delete(fileName); LoadMp3Files(); txtMessages.Text = $"File Converted to MP3: '{saveMp3File}'"; timerVideo.Enabled = false; txtMessages.BackColor = Color.White; if (chkAutoplay.Checked) { PlayMp3(saveMp3File); } return; } }
private string disintegrateVideoToAudioTest(string userRegistrationVideoLocation) { if (String.IsNullOrWhiteSpace(userRegistrationVideoLocation) == false) { var userRegistrationAudioLocation = "userAudioTest.wav"; var extractHelper = new NReco.VideoConverter.FFMpegConverter(); Stream audioStream = new MemoryStream(); extractHelper.ConvertMedia(userRegistrationVideoLocation, audioStream, "wav"); audioStream.Position = 0; uploadFileToStorage(audioStream, userRegistrationAudioLocation); extractHelper.Abort(); return(string.Concat(storedFilePrefix, userRegistrationAudioLocation)); } else { return(string.Empty); } }
public AudioData ExtractAndSaveAudio() { var converter = new NReco.VideoConverter.FFMpegConverter(); var audioFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".mp3"); string storageKey = Guid.NewGuid().ToString(); converter.ConvertMedia(videoFilePath, audioFilePath, "mp3"); var durationInSeconds = new Mp3FileReader(audioFilePath).TotalTime.TotalSeconds; return(new AudioData { FilePath = audioFilePath, AudioFormat = "mp3", DurationInSeconds = durationInSeconds }); }
private Stream disintegrateVideoToAudio(string userRegistrationVideoLocation) { if (String.IsNullOrWhiteSpace(userRegistrationVideoLocation) == false) { //var userRegistrationAudioFileName = "userAudio.wav"; var extractHelper = new NReco.VideoConverter.FFMpegConverter(); Stream audioStream = new MemoryStream(); extractHelper.ConvertMedia(userRegistrationVideoLocation, audioStream, "wav"); audioStream.Position = 0; //uploadFileToStorage(audioStream, userRegistrationAudioFileName); //extractHelper.Abort(); return(audioStream); } else { return(null); } }
public async void DownloadAsyncAudio(string url, Label labelLoadBar) { try { labelLoadBar.Content = "Starting Download"; var id = YoutubeClient.ParseVideoId(url); var client = new YoutubeClient(); var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id); var video = await client.GetVideoAsync(id); var mp4FileTitle = video.Title; var streamInfo = streamInfoSet.Muxed.FirstOrDefault(quality => quality.VideoQualityLabel == "360p"); var ext = streamInfo.Container.GetFileExtension(); string mp4Path = Directory.GetCurrentDirectory() + "\\Download\\" + mp4FileTitle + "." + ext; await client.DownloadMediaStreamAsync(streamInfo, mp4Path); labelLoadBar.Content = "Starting cover to mp3"; var convert = new NReco.VideoConverter.FFMpegConverter(); string mp3Path = Directory.GetCurrentDirectory() + "\\Download\\" + mp4FileTitle + ".mp3"; convert.ConvertMedia(mp4Path.Trim(), mp3Path.Trim(), "mp3"); labelLoadBar.Content = "Saving Url"; TagFile(url, mp3Path); labelLoadBar.Content = "Tmp File Removing"; System.IO.File.Delete(mp4Path); labelLoadBar.Content = "Audio is Ready"; } catch (Exception e) { MessageBox.Show(e.ToString()); } }
public static async void Convert(string path) { string[] files = Directory.GetFiles(path, "*.webm", SearchOption.AllDirectories); int total = files.Length; for (int i = 0; i < files.Length; i++) { string source = files[i]; string output = files[i].Replace(".webm", ".mp4"); var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); ffMpeg.ConvertMedia(source, output, NReco.VideoConverter.Format.mp4); Console.WriteLine("Converted " + i + " / " + total); GC.Collect(); await Task.Delay(100); } }
private void timer1_Tick(object sender, System.EventArgs e) { myTimer.Stop(); Console.WriteLine("Текущее время: " + DateTime.Now.ToLongTimeString()); _screenCaptureJob.Stop(); _screenCaptureJob.Stop(); var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); ffMpeg.ConvertMedia(file, null, // autodetect by input file extension "output.mp4", null, // autodetect by output file extension new NReco.VideoConverter.ConvertSettings() { // CustomOutputArgs = " -filter_complex \"[0] yadif=0:-1:0,scale=iw*sar:ih,scale='if(gt(a,16/9),1280,-2)':'if(gt(a,16/9),-2,720)'[scaled];[scaled] pad=1280:720:(ow-iw)/2:(oh-ih)/2:black \" -c:v libx264 -c:a mp3 -ab 128k " CustomOutputArgs = " -vcodec msmpeg4v2 -c:v libx264 -crf 24 -r 20 -b:v 500k" } ); }
public JsonResult UploadAPI() { for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; //Uploaded file //Use the following properties to get file's name, size and MIMEType int fileSize = file.ContentLength; string filePath = file.FileName; string fileName = filePath.Split('\\').LastOrDefault(); string fileExtension = fileName.Split('.').LastOrDefault(); string mimeType = file.ContentType; System.IO.Stream fileContent = file.InputStream; //To save file, use SaveAs method if (!mimeType.Equals("video/mp4") || !fileExtension.Equals("mp4")) { var ffmpeg = new NReco.VideoConverter.FFMpegConverter(); var original_video_src = Server.MapPath("~" + Settings.Default.MS_VIDEO_UPLOAD_SRC) + "Orig_" + fileName; var converted_video_src = Server.MapPath("~" + Settings.Default.MS_VIDEO_UPLOAD_SRC) + fileName; file.SaveAs(original_video_src); ffmpeg.ConvertMedia(original_video_src, converted_video_src, "mp4"); if (System.IO.File.Exists(original_video_src)) { System.IO.File.Delete(original_video_src); } } else { var converted_video_src = Server.MapPath("~" + Settings.Default.MS_VIDEO_UPLOAD_SRC) + fileName; file.SaveAs(converted_video_src); } } return(Json("Uploaded " + Request.Files.Count + " files")); }
private void btnConvert_Click(object sender, EventArgs e) { var convert = new NReco.VideoConverter.FFMpegConverter(); convert.ConvertMedia(txtPathVideo.Text.Trim(), txtSaveto.Text.Trim(), "mp3"); }
private async void BtnDescargar_Click(object sender, RoutedEventArgs e) { //nuevo cliente de Youtube var client = new YoutubeClient(); //lee la dirección de youtube que le escribimos en el textbox var videoId = NormalizeVideoId(txtYoutubeURL.Text); var video = await client.GetVideoAsync(videoId); var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId); // Busca la mejor resolución en la que está disponible el video var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality(); // Compone el nombre que tendrá el video en base a su título y extensión var fileExtension = streamInfo.Container.GetFileExtension(); var fileName = $"{video.Title}.{fileExtension}"; //TODO: Reemplazar los caractéres ilegales del nombre fileName = CleanInput(fileName); //Activa el timer para que el proceso funcione de forma asincrona //tmrVideo.Enabled = true; // mensajes indicando que el video se está descargando //txtMensaje.Text = "Descargando el video ... "; MessageBox.Show("Descargando... porfavor espere..."); pbStatus.Visibility = Visibility.Visible; txtdescargando.Visibility = Visibility.Visible; //TODO: se pude usar una barra de progreso para ver el avance //using (ProgressBar progress = new ProgressBar()) //Empieza la descarga await client.DownloadMediaStreamAsync(streamInfo, fileName); //Ya descargado se inicia la conversión a MP3 var Convert = new NReco.VideoConverter.FFMpegConverter(); //Especificar la carpeta donde se van a guardar los archivos, recordar la \ del final String SaveMP3File = @"C:\DescargasPF\" + fileName.Replace(".mp4", ".mp3"); //Guarda el archivo convertido en la ubicación indicada Convert.ConvertMedia(fileName, SaveMP3File, "mp3"); //Si el checkbox de solo audio está chequeado, borrar el mp4 despues de la conversión //if (ckbAudio.Checked) // File.Delete(fileName); //Indicar que se terminó la conversion MessageBox.Show("Archivo descargado y convertido"); pbStatus.Visibility = Visibility.Hidden; txtdescargando.Visibility = Visibility.Hidden; //TODO: Cargar el MP3 al reproductor o a la lista de reproducción mediaPlayer.Open(new Uri(SaveMP3File)); Cancioneslist CancionesJson = new Cancioneslist(); CancionesJson.Nombre = fileName; CancionesJson.Ubicacion = SaveMP3File; string salida = JsonConvert.SerializeObject(CancionesJson); FileStream stream = new FileStream("Biblioteca.Json", FileMode.Append, FileAccess.Write); StreamWriter writer = new StreamWriter(stream); writer.WriteLine(salida); writer.Close(); MessageBox.Show("Ingresado Exitosamente!!"); }
private void ConvertToMp3(string filePath) { //Start converting into .mp3 convertTask = Task.Factory.StartNew(async() => { lblStatus.Invoke((MethodInvoker)(() => { isConverting = true; pbLoad.BackgroundImage = null; pbLoad.Image = Properties.Resources.load25x25; lblStatus.Text = "Converting..."; })); FFMpegConverter = new NReco.VideoConverter.FFMpegConverter(); FFMpegConverter.FFMpegToolPath = BLIO.rootFolder + "\\Video\\"; FFMpegConverter.ConvertProgress += (o, args) => { try { pbDownload.Invoke((MethodInvoker)(() => { pbDownload.Value = (int)Math.Round((args.Processed.TotalMilliseconds / args.TotalDuration.TotalMilliseconds) * 100); if (pbDownload.Value >= 99) { tmrCheckProgress.Start(); } })); } catch (InvalidOperationException) { }//Thread aborted, can't do things with the controls anymore Console.WriteLine(string.Format("Progress: {0} / {1}\r\n", args.Processed, args.TotalDuration)); }; pathToSong = GetValidFilePath(BLSettings.MP3Path, theVideo.Title, "." + BLSettings.AudioType); try { //Create directory in case it doesnt exist Directory.CreateDirectory(Path.GetDirectoryName(pathToSong)); await Task.Run(() => FFMpegConverter.ConvertMedia(filePath, pathToSong, BLSettings.AudioType)); if (File.Exists(pathToSong)) { DownloadHistory historyRecord = new DownloadHistory(); historyRecord.ChannelTitle = theVideo.Author; historyRecord.DownloadDate = DateTime.Now.ToString(); historyRecord.Duration = theVideo.Duration.ToString(); historyRecord.ThumbnailLink = "http://img.youtube.com/vi/" + theVideo.Id + "/0.jpg"; historyRecord.Title = theVideo.Title; historyRecord.VideoId = theVideo.Id; UCHistory history = (UCHistory)this.Parent.Parent.Parent.Controls["ucHistory"]; DownloadItem item = new DownloadItem(historyRecord); item.theVideo = theVideo; history.AddHistory(item); BLHistory.InsertRecord(historyRecord); if (BLSettings.KeepMp4) { File.Move(BLIO.rootFolder + "\\Video\\" + RemoveIllegalCharacters(Path.GetFileNameWithoutExtension(filePath)) + "." + BLSettings.VideoType, BLSettings.VideoPath + "\\" + RemoveIllegalCharacters(Path.GetFileNameWithoutExtension(filePath)) + "." + BLSettings.VideoType); } else { File.Delete(BLIO.rootFolder + "\\Video\\" + RemoveIllegalCharacters(filePath) + "." + BLSettings.VideoType); } } } catch (NullReferenceException) { } //Nullreference exception occurs when aborting the convert task }, ctsConvert.Token); }
public static void ConvertMp4ToMp3(string inputFile, string outPutFile) { var cv = new NReco.VideoConverter.FFMpegConverter(); cv.ConvertMedia(inputFile, outPutFile, "mp3"); }
private async void MaterialFlatButton1_Click(object sender, EventArgs e) { SaveThumbnailCheckBox.Hide(); materialProgressBar1.Show(); ProgressLabel.Show(); materialProgressBar1.Value = 0; materialFlatButton1.Hide(); materialFlatButton2.Hide(); var client = new YoutubeClient(); var videoId = YoutubeClient.ParseVideoId(SearchBoxInput.Text); ProgressLabel.Text = "Searching Video"; materialProgressBar1.Value = materialProgressBar1.Value + 1; var video = await client.GetVideoAsync(videoId); ProgressLabel.Text = "Found Video"; materialProgressBar1.Value = materialProgressBar1.Value + 1; var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId); var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality(); var fileExtension = streamInfo.Container.GetFileExtension(); var fileName = $"{video.Title} - {video.Author}.{fileExtension}"; fileName = ReplaceInvalidChars(fileName); ProgressLabel.Text = "Downloading Video"; bool SaveThumbnail = SaveThumbnailCheckBox.Checked; int TempProgressBarValue; if (SaveThumbnail) { TempProgressBarValue = 1; } else { TempProgressBarValue = 2; } materialProgressBar1.Value = materialProgressBar1.Value + TempProgressBarValue; await client.DownloadMediaStreamAsync(streamInfo, fileName); ProgressLabel.Text = "Converting to MP3"; materialProgressBar1.Value = materialProgressBar1.Value + 4; var Convert = new NReco.VideoConverter.FFMpegConverter(); var MP3FolderPath = "C:/Users/" + Environment.UserName + "/Music/mPlayer/"; String SaveMP3File = MP3FolderPath + fileName.Replace(".mp4", ".mp3"); Convert.ConvertMedia(fileName, SaveMP3File, "mp3"); if (SaveThumbnail) { ProgressLabel.Text = "Saving Thumbnail"; materialProgressBar1.Value = materialProgressBar1.Value + 1; var thumbnail = video.Thumbnails.HighResUrl; using (WebClient webClient = new WebClient()) { webClient.DownloadFile(thumbnail, "C:/Users/" + Environment.UserName + "/Music/mPlayer/Data/Thumbnails/" + fileName.Replace(".mp4", string.Empty) + ".jpg");; } } ProgressLabel.Text = "Cleaning Old Files"; materialProgressBar1.Value = materialProgressBar1.Value + 1; File.Delete(fileName); ProgressLabel.Text = "Done. Refresh your Music!"; materialProgressBar1.Value = materialProgressBar1.Value + 1; materialFlatButton1.Show(); materialFlatButton2.Show(); }
private async void Button9_ClickAsync(object sender, EventArgs e) { //nuevo cliente de Youtube var client = new YoutubeClient(); //lee la dirección de youtube que le escribimos en el textbox var videoId = NormalizeVideoId(textBox2.Text); //normaliza var video = await client.GetVideoAsync(videoId); //descarga el video var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId); //descarga la informacion del video // Busca la mejor resolución en la que está disponible el video var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality(); //descarga el video con la maxima calidad // Compone el nombre que tendrá el video en base a su título y extensión var fileExtension = streamInfo.Container.GetFileExtension(); //mira la extencion mp4 var fileName = $"{video.Title}.{fileExtension}"; //agrega el titulo del video y la extencion mp4 //TODO: Reemplazar los caractéres ilegales del nombre //fileName = RemoveIllegalFileNameChars(fileName); //Activa el timer para que el proceso funcione de forma asincrona timer1.Enabled = true; // mensajes indicando que el video se está descargando labelEstadoDescarga.Text = "Descargando el video ... "; //mensaje //TODO: se pude usar una barra de progreso para ver el avance //using (var progress = new ProgressBar()) //Empieza la descarga await client.DownloadMediaStreamAsync(streamInfo, fileName); //empieza la descarga //Ya descargado se inicia la conversión a MP3 var Convert = new NReco.VideoConverter.FFMpegConverter(); //convierte el video //Especificar la carpeta donde se van a guardar los archivos, recordar la \ del final String SaveMP3File = @"C:\DescargasMP3\" + fileName.Replace(".mp4", ".mp3"); //en donde se va a guardar el archivo //Guarda el archivo convertido en la ubicación indicada Convert.ConvertMedia(fileName, SaveMP3File, "mp3"); //Si el checkbox de solo audio está chequeado, borrar el mp4 despues de la conversión if (checkBox1.Checked) //funcion checkbox { File.Delete(fileName); // si quemos solo el audio manda a borrar el mp4 y nos quedamos con el mp3 } //Indicar que se terminó la conversion labelEstadoDescarga.Text = "Archivo Convertido en MP3"; timer1.Enabled = false; labelEstadoDescarga.BackColor = Color.White; //TODO: Cargar el MP3 al reproductor o a la lista de reproducción //CargarMP3s(); //Se puede incluir un checkbox para indicar que de una vez se reproduzca el MP3 //if (ckbAutoPlay.Checked) // ReproducirMP3(SaveMP3File); //Declarar un objeto de Clase cliente ClassCancion cancionJson = new ClassCancion(); //Asignarle valores al cliente cancionJson.DireccionCancion = SaveMP3File; cancionJson.NombreCancion = fileName.Replace("Mp4", "MP3"); //Convertir el objeto en una cadena JSON string salida = JsonConvert.SerializeObject(cancionJson); //Guardar el archivo de texto, con extension Json FileStream stream = new FileStream("Cancion.json", FileMode.Append, FileAccess.Write); StreamWriter writer = new StreamWriter(stream); MessageBox.Show("La Canción: " + cancionJson.NombreCancion + " Se Registro Correctamente"); writer.WriteLine(salida); writer.Close(); nombrecancion = cancionJson.NombreCancion; rutascancion = cancionJson.DireccionCancion; object rowmidex = dataGridView1.CurrentRow.Index; reproductor.URL = cancionJson.DireccionCancion;; string[] stringArray = new string[] { rutascancion }; reproductor.URL = stringArray[0]; ////////////////////////////////////////// return; }
public static void ConvertToWav(string infile, string outfile) { var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); ffMpeg.ConvertMedia(infile, outfile, "wav"); }