Esempio n. 1
0
        void ConvertFile(string file)
        {
            try
            {
                var ffMpeg      = new NReco.VideoConverter.FFMpegConverter();
                var ffMpegInput = new NReco.VideoConverter.FFMpegInput(file);

                ConvertSettings csettings = new ConvertSettings();
                if (EnableResize.Checked == true)
                {
                    csettings.SetVideoFrameSize((int)Xaxis.Value, (int)Yaxis.Value);
                }


                if (FormatChooser.SelectedIndex == 0)
                {
                    ffMpeg.ConvertMedia(file, ffMpegInput.Format, file + "Converted.avi", Format.avi, csettings);
                }
                else if (FormatChooser.SelectedIndex == 1)
                {
                    ffMpeg.ConvertMedia(file, ffMpegInput.Format, file + "Converted.mp4", Format.mp4, csettings);
                }
                else if (FormatChooser.SelectedIndex == 2)
                {
                    ffMpeg.ConvertMedia(file, ffMpegInput.Format, file + "Converted.m4v", Format.m4v, csettings);
                }
                else if (FormatChooser.SelectedIndex == 3)
                {
                    ffMpeg.ConvertMedia(file, ffMpegInput.Format, file + "Converted.gif", Format.gif, csettings);
                }
                else if (FormatChooser.SelectedIndex == 4)
                {
                    ffMpeg.ConvertMedia(file, ffMpegInput.Format, file + "Converted.mov", Format.mov, csettings);
                }
                else if (FormatChooser.SelectedIndex == 5)
                {
                    ffMpeg.ConvertMedia(file, ffMpegInput.Format, file + "Converted.wmv", Format.wmv, csettings);
                }
                else if (FormatChooser.SelectedIndex == 6)
                {
                    ffMpeg.ConvertMedia(file, ffMpegInput.Format, file + "Converted.swf", Format.swf, csettings);
                }
                else if (FormatChooser.SelectedIndex == 7)
                {
                    ffMpeg.ConvertMedia(file, ffMpegInput.Format, file + "Converted.ogg", Format.ogg, csettings);
                }
                else if (FormatChooser.SelectedIndex == 8)
                {
                    ffMpeg.ConvertMedia(file, ffMpegInput.Format, file + "Converted.mpeg", Format.mpeg, csettings);
                }
                else //Nothing selected? Default to .avi format.
                {
                    ffMpeg.ConvertMedia(file, ffMpegInput.Format, file + "Converted.avi", ffMpegInput.Format, csettings);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception error has occured:\n" + e.Message.ToString(), Title);
            }
        }
Esempio n. 2
0
        public async Task PobierzAsync()
        {
            try
            {
                var client = new YoutubeClient();
                var url    = textBox1.Text;
                var id     = YoutubeClient.ParsePlaylistId(url);

                var playlist = await client.GetPlaylistAsync(id);

                foreach (var vid in playlist.Videos)
                {
                    var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(vid.Id);

                    var streamInfo = streamInfoSet.Audio.WithHighestBitrate();
                    var ext        = streamInfo.Container.GetFileExtension();
                    var video      = await client.GetVideoAsync(vid.Id);

                    string sourcePath = $"C:/YTMP3/{video.Title}.{ext}";
                    string outputPath = $"C:/YTMP3/{video.Title}.mp3";
                    await client.DownloadMediaStreamAsync(streamInfo, sourcePath);

                    var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                    ffMpeg.ConvertMedia(sourcePath, outputPath, Format.mp4);

                    File.Delete(sourcePath);
                }
                MessageBox.Show("Pobrałem.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Coś poszło nie tak." + Environment.NewLine + ex.Message);
            }
        }
Esempio n. 3
0
        // convert directory of png images to video
        // overloaded for use with progress bar
        public static void png_to_mp4(string pngTempDir, string outFile, ProgressWindow progform, string fps = "4")
        {
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
            var outS   = new NReco.VideoConverter.ConvertSettings();

            outS.CustomInputArgs = "-framerate " + fps;
            outS.CustomInputArgs = "-y " + outS.CustomInputArgs;
            outS.VideoFrameSize  = sys.convsettings["size"];

            //outS.VideoFrameRate = 10;

            /* Got NReco to work a few notes:
             * 1) %05d is the bash syntax for a number that's padded with 0's for 5 digits. i.e. 00349
             * 2) ffmpeg only looks for stills with the file number of 0~4. ie. imagename000.png. If it doesn't find it, it gives "file not found" error.
             * 3) NReco can be found in the folder.
             * conv.convert(); in program to call.
             */

            ffMpeg.ConvertProgress += (o, args) => progHandler(o, args, progform);

            // actual conversion command
            ffMpeg.ConvertMedia(pngTempDir + @"%04d.png", "image2", outFile + @"." + sys.convsettings["format"], sys.convsettings["format"], outS);

            progform.setProgress(100);
            progform.Update();
        }
        public ActionResult Index()
        {
            string url     = "https://www.youtube.com/watch?v=bDuzU4XLEEs";
            var    youTube = YouTube.Default;       // starting point for YouTube actions
            var    video   = youTube.GetVideo(url); // gets a Video object with info about the video

            //System.IO.File.WriteAllBytes(@"C:\Downloads\" + video.FullName, video.GetBytes());
            var videoName = @"C:\Downloads\" + video.FullName;
            var ffmpeg    = new NReco.VideoConverter.FFMpegConverter();

            using (System.IO.Stream stream = new System.IO.MemoryStream(video.GetBytes(), 0, video.GetBytes().Length))
            {
                stream.Write(video.GetBytes(), 0, video.GetBytes().Length);

                ffmpeg.ConvertLiveMedia(stream, Format.mp4, @"C:\Downloads\result2.gif", Format.gif, new ConvertSettings()
                {
                    VideoFrameRate = 1, MaxDuration = 10
                });
            }
            ffmpeg.ConvertMedia(videoName, null, @"C:\Downloads\result.gif", null, new ConvertSettings()
            {
                VideoFrameRate = 1, MaxDuration = 10
            });

            var k = ffmpeg.ConvertLiveMedia(video.Stream(), Format.mp4, @"C:\Downloads\result2.gif", null, new ConvertSettings()
            {
                VideoFrameRate = 1, MaxDuration = 10
            });

            k.Start();



            return(View());
        }
Esempio n. 5
0
        private async Task MainAsync()
        {
            clsBiblioteca biblioteca = new clsBiblioteca();
            //Nuevo Cliente de YouTube
            var client = new YoutubeClient();
            //Lee la URL 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
            ckbAudio.Enabled = true;
            // mensajes indicando que el video se está descargando
            label4.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 = @"C:\Users\Ramirez\Documents\Visual Studio 2015\Projects\ProyectoFinal3\ProyectoFinal3\mp3" + fileName.Replace(".mp4", ".mp3");

            biblioteca.Url     = SaveMP3File;
            biblioteca.Cancion = fileName;
            //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("Vídeo convertido correctamente.");
            label4.Text      = "";
            txtURL.Text      = "";
            ckbAudio.Enabled = false;

            biblioteca.Letra   = URlLyries;
            biblioteca.Portada = URLportada;
            biblioteca.Id      = contador.ToString();
            GuardarBiblioteca(biblioteca);
            // GuardarCancion(biblioteca);
            //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;
        }
Esempio n. 6
0
        public void ConvertMP4File()
        {
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            string[] extention = Path.GetExtension(mp3FilePath.Text).Split('.');
            ffMpeg.ConvertMedia(mp4FilePath.Text, mp3FilePath.Text, extention[1]);
            MessageBox.Show("Well done!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 7
0
        public void ConvertVideoToMp4()
        {
            string sourceVideoFolder = ConfigurationSettings.AppSettings.Get("PhysicalSiteDataDirectory") + @"\video\";
            string videoFull         = inputVideo.Split('/')[3];
            string videoName         = videoFull.Split('.')[0];

            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.ConvertMedia(sourceVideoFolder + videoFull, sourceVideoFolder + videoName + ".mp4", Format.mp4);
        }
Esempio n. 8
0
        // NReco.VideoConverter to convert mp4 to mp3 file.
        public static string Mp4_To_mp3()
        {
            // Carry out conversion.
            var    ConvertVideo = new NReco.VideoConverter.FFMpegConverter();
            string inputFile    = @"C:\Users\Dell XPS\Documents\GitHub\Cognitive-Speech-STT-ServiceLibrary\Input Files\ForStephane.mp4";
            string outputFile   = @"C:\Users\Dell XPS\Documents\GitHub\Cognitive-Speech-STT-ServiceLibrary\Output Files\ForStephane.mp3";

            ConvertVideo.ConvertMedia(inputFile, outputFile, "mp3");
            return(outputFile);
        }
Esempio n. 9
0
        static string DownloadVideo(string link, string dir)
        {
            var    youTube = YouTube.Default;
            var    video   = youTube.GetVideo(link);
            string file    = dir + @"\" + video.FullName;
            var    ffMpeg  = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.ConvertMedia(file, "video.mp3", Format.raw_data);
            System.IO.File.WriteAllBytes(file, video.GetBytes());
            return(file);
        }
Esempio n. 10
0
        public ActionResult Index()
        {
            string url     = "https://www.youtube.com/watch?v=kIQypcFvGNM";
            var    youTube = YouTube.Default;       // starting point for YouTube actions
            var    video   = youTube.GetVideo(url); // gets a Video object with info about the video

            System.IO.File.WriteAllBytes(@"C:\Downloads\" + video.FullName, video.GetBytes());
            var videoName = @"C:\Downloads\" + video.FullName;
            var ffmpeg    = new NReco.VideoConverter.FFMpegConverter();

            ffmpeg.ConvertMedia(videoName, null, @"C:\Downloads\result.gif", null, new ConvertSettings());
            return(View());
        }
Esempio n. 11
0
        private void button2_Click(object sender, EventArgs e)
        {
            string input = @"C:\Users\a\Videos\Debut\Untitled 7.avi";

            string output = "C:\\test3.avi";

            var setting = new NReco.VideoConverter.ConvertSettings();

            setting.SetVideoFrameSize(1280, 720);
            setting.CustomInputArgs = "-ss 00:00:00 -t 00:00:10";
            // setting.CustomOutputArgs = "-vf vflip";
            setting.CustomOutputArgs = "-vf \"movie=logo.png [watermark]; [in][watermark] overlay=main_w-overlay_w-10:main_h-overlay_h-10 [out]\"";


            //            Top left corner
            //ffmpeg -i inputvideo.avi -vf "movie=watermarklogo.png [watermark]; [in][watermark] overlay=10:10 [out]" outputvideo.flv

            //Top right corner
            //ffmpeg -i inputvideo.avi -vf "movie=watermarklogo.png [watermark]; [in][watermark] overlay=main_w-overlay_w-10:10 [out]" outputvideo.flv

            //Bottom left corner
            //ffmpeg -i inputvideo.avi -vf "movie=watermarklogo.png [watermark]; [in][watermark] overlay=10:main_h-overlay_h-10 [out]" outputvideo.flv

            //Bottom right corner
            //ffmpeg -i inputvideo.avi -vf "movie=watermarklogo.png [watermark]; [in][watermark] overlay=main_w-overlay_w-10:main_h-overlay_h-10 [out]" outputvideo.flv



            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.ConvertProgress += FfMpeg_ConvertProgress;

            ffMpeg.GetVideoThumbnail(input, "temp.jpg", 10.0f);
            System.IO.FileStream hStream = new System.IO.FileStream("temp.jpg", System.IO.FileMode.Open);
            this.pictureBox1.Image = Image.FromStream(hStream);
            // FileStream を閉じる (正しくは オブジェクトの破棄を保証する を参照)
            hStream.Close();
            return;

            //ffMpeg.ConvertMedia(input, null, output, null, setting);

            ffMpeg.ConvertMedia(input, null, output, NReco.VideoConverter.Format.mp4, setting);
            //


            NReco.VideoConverter.ConcatSettings set = new NReco.VideoConverter.ConcatSettings();
            set.SetVideoFrameSize(640, 480);
            //ffMpeg.ConcatMedia(_fileNames, videoRootPath + tobename + ".mp4", NReco.VideoConverter.Format.mp4, set);

            this.Text = "FINISH";
        }
        private void BtnConvert_Click(object sender, EventArgs e)
        {
            this.btnBrowse.Enabled      = false;
            this.btnConvert.Enabled     = false;
            this.btnDestination.Enabled = false;
            this.listAudio.Items.Clear();
            int i = 0;

            this.lblCurrentFile.Visible  = true;
            this.pbProgress.Visible      = true;
            this.listVideo.Visible       = true;
            this.listAudio.Visible       = true;
            this.pbTotalProgress.Visible = true;
            this.pbProgress.Maximum      = 100;
            this.pbTotalProgress.Maximum = 100;
            this.totalItem             = this.listVideo.Items.Count;
            this.pbTotalProgress.Value = 0;
            this.processedItem         = 0;
            foreach (string file in this.input)
            {
                try
                {
                    this.pbProgress.Value = 0;
                    this.processedItem    = i + 1;
                    //var item = this.listVideo.Items[i];
                    //string outputFile = item.ToString();
                    var outputFile = Path.GetFileNameWithoutExtension(file); //outputFile.Substring(0, outputFile.LastIndexOf('.'));
                    this.lblCurrentFile.Text = "Converting: " + file;
                    var       ConvertToAudio = new NReco.VideoConverter.FFMpegConverter();
                    var       ffprobe        = new NReco.VideoInfo.FFProbe();
                    MediaInfo videoInfo      = ffprobe.GetMediaInfo(file);
                    this.totalSeconds = videoInfo.Duration.Milliseconds;
                    ConvertToAudio.ConvertProgress += new EventHandler <ConvertProgressEventArgs>(this.UpdateProgress);
                    ConvertToAudio.ConvertMedia(file, this.txtAudio.Text + "\\" + outputFile + ".mp3", "mp3");
                    this.listAudio.Items.Add(this.txtAudio.Text + "\\" + outputFile + ".mp3");
                    i++;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    i++;
                }
            }
            this.lblCurrentFile.Text    = "Completed";
            this.btnBrowse.Enabled      = true;
            this.btnConvert.Enabled     = true;
            this.btnDestination.Enabled = true;
        }
Esempio n. 13
0
        private void OpenFile_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.Filter = "All Files (*.*)|*.*|mpg (*.mpg*.vob) | *.mpg;*.vob|avi (*.avi) | *.avi|Divx (*.divx) | *.divx|wmv (*.wmv)| *.wmv|QuickTime (*.mov)| *.mov|MP4 (*.mp4) | *.mp4|AVCHD (*.m2ts*.ts*.mts*m2t)|*.m2ts;*.ts;*.mts;*.m2t|wav (*.wav)|*.wav|MP3 (*.mp3)|*.mp3|WMA (*.wma)|*.wma||";
            if (openFileDialog.ShowDialog() == true)
            {
                string strFile = openFileDialog.FileName;
                Uri    pathUri = new Uri(strFile);
                View.Source = pathUri;
                InputFile   = strFile;
                Outputfile  = InputFile.Substring(0, InputFile.LastIndexOf("."));

                var ConvertVideo = new NReco.VideoConverter.FFMpegConverter();
                ConvertVideo.ConvertMedia(InputFile, Outputfile + ".WAV", "WAV");
            }
        }
Esempio n. 14
0
        public void extractVideo()
        {
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.FFMpegToolPath = "ffmpeg";
            ffMpeg.ConvertMedia(
                "input.mp4",
                "mp4",
                "output.mp3",
                "mp3",
                new ConvertSettings {
                AudioCodec = "libmp3lame", CustomOutputArgs = "-vn -ar 44100 -ac 2 -ab 192K"
            }
                );
            Console.WriteLine("Ok");
        }
Esempio n. 15
0
        public void Create(string input)
        {
            if (File.Exists(output))
            {
                File.Delete(output);
            }

            transparent.Save("logo.png", System.Drawing.Imaging.ImageFormat.Png);

            var setting = new NReco.VideoConverter.ConvertSettings();

            setting.SetVideoFrameSize(1280, 720);
            setting.CustomInputArgs = "-ss 00:00:00 -t 00:00:05";
            // setting.CustomOutputArgs = "-vf vflip";
            setting.CustomOutputArgs = "-vf \"movie=logo.png [watermark]; [in][watermark] overlay=10:10 [out]\"";
            //setting.CustomOutputArgs = "-vf \"setsar=sar=1/1\"";

            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.ConvertMedia(input, null, tempout, NReco.VideoConverter.Format.mp4, setting);

            string cmdParams = "-i opening.mp4 -i temp.mp4 -filter_complex \"[0:0] [1:0] concat=n=2:v=1:a=0:unsafe=1\" " + output;

            try {
                Execute("ffmpeg.exe", cmdParams);


                MessageBox.Show("FINISHED");
            }
            catch
            {
                MessageBox.Show("結合失敗。");
            }


            //NReco.VideoConverter.ConcatSettings set = new NReco.VideoConverter.ConcatSettings();
            //set.ConcatAudioStream = false;

            ////set.SetVideoFrameSize(640, 480);
            //string[] inputfiles = { "opening.mp4", tempout };
            //ffMpeg.ConcatMedia(inputfiles, output, NReco.VideoConverter.Format.mp4, set);
            //this.Text = "FINISH";
        }
Esempio n. 16
0
        // convert directory of png images to video
        public static Boolean png_to_mp4(string pngTempDir, string outFile, string fps = "4")
        {
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
            var outS   = new NReco.VideoConverter.ConvertSettings();

            outS.CustomInputArgs = "-framerate " + fps;
            outS.CustomInputArgs = "-y " + outS.CustomInputArgs;
            outS.VideoFrameSize  = sys.convsettings["size"];

            /* Got NReco to work a few notes:
             * 1) %05d is the bash syntax for a number that's padded with 0's for 5 digits. i.e. 00349
             * 2) ffmpeg only looks for stills with the file number of 0~4. ie. imagename000.png. If it doesn't find it, it gives "file not found" error.
             * 3) NReco can be found in the folder.
             * conv.convert(); in program to call.
             */

            ffMpeg.ConvertMedia(pngTempDir + @"%04d.png", "image2", outFile + @"." + sys.convsettings["format"], sys.convsettings["format"], outS);

            return(false);
        }
Esempio n. 17
0
        //Generate Transcript Button
        private void button2_Click(object sender, EventArgs e)
        {
            string outputfileName = OutputFile + ".mp3";

            //extract mp3 from mp4 file
            var ConvertVideo = new NReco.VideoConverter.FFMpegConverter();

            ConvertVideo.ConvertMedia(InputFile, outputfileName, "mp3");

            //convert mp3 to wav file
            string InputAudioFilePath  = outputfileName;
            string OutputAudioFilePath = @"C:\Users\kliu7\Documents\Bitcamp2018\output.wav";

            Console.WriteLine(InputAudioFilePath);


            using (Mp3FileReader reader = new Mp3FileReader(InputAudioFilePath, wf => new Mp3FrameDecompressor(wf)))
            {
                WaveFileWriter.CreateWaveFile(OutputAudioFilePath, reader);
            }
        }
Esempio n. 18
0
        protected void AjaxFileUpload1_UploadComplete(object sender, AjaxFileUploadEventArgs e)
        {
            string str_filename, str_field;
            string path = Server.MapPath("~/videos/") + e.FileName;

            str_filename = e.FileName;
            string str_file_save  = str_filename.Replace(".wmv", ".mp4");
            string str_filesize   = e.FileSize.ToString();
            Int32  str_filesizemb = Convert.ToInt32(str_filesize) / 1024;

            str_field = e.FileId;

            //using (var insert_material = new db_transcriptEntities())
            //{

            //    var items_user = new inf_material
            //    {
            //        expediente = "00001",
            //        sesion = "001",
            //        archivo = str_filename,
            //        bits = Convert.ToInt32(str_filesizemb),
            //        fecha_registro = DateTime.Now,
            //        id_estatus_material = 1,
            //        id_usuario = id_user,

            //    };
            //    insert_material.inf_material.Add(items_user);
            //    insert_material.SaveChanges();
            //}

            AjaxFileUpload1.SaveAs(path);

            //ReturnVideo(path);
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.ConvertMedia(path, "videos/" + str_file_save, Format.mp4);
            lbl_mnsj.Visible = true;
            lbl_mnsj.Text    = "Videa a mp4 con Exito";
            //Session["ss_id_user"] = id_user;
        }
        private static void DoWork(object sender, DoWorkEventArgs e)
        {
            // Long running background operation

            using (var edm_material = new db_transcriptEntities())
            {
                var i_material = (from c in edm_material.inf_material
                                  where c.id_estatus_material == 6
                                  select c).ToList();

                foreach (var item in i_material)
                {
                    string str_path_ini, str_path_fin;

                    using (db_transcriptEntities data_path = new db_transcriptEntities())
                    {
                        var count_path = (from c in data_path.inf_ruta_videos
                                          select c).FirstOrDefault();

                        str_path_fin = count_path.desc_ruta_fin;
                        str_path_ini = count_path.desc_ruta_fin + "\\" + str_video;
                    }

                    str_path_ini = str_path_fin + "\\" + item.archivo.ToString().Replace(".mp4", ".wmv");

                    string str_file_save = str_path_ini.ToString();
                    string str_save_file = str_path_ini.ToString().Replace(".wmv", ".mp4");
                    var    ffMpeg        = new NReco.VideoConverter.FFMpegConverter();

                    var ffProbe   = new NReco.VideoInfo.FFProbe();
                    var videoInfo = ffProbe.GetMediaInfo(str_file_save);

                    string str_duration_wmv = videoInfo.Duration.Hours + ":" + videoInfo.Duration.Minutes + ":" + videoInfo.Duration.Seconds;

                    try
                    {
                        using (var data_mat = new db_transcriptEntities())
                        {
                            var items_mat = (from c in data_mat.inf_material
                                             where c.sesion == str_session
                                             select c).FirstOrDefault();

                            items_mat.id_estatus_material = 6;

                            data_mat.SaveChanges();
                        }

                        var two_user = new int?[] { 6 };

                        ffMpeg.ConvertMedia(str_file_save, str_save_file, Format.mp4);


                        using (var data_mat = new db_transcriptEntities())
                        {
                            var items_mat = (from c in data_mat.inf_material
                                             where c.sesion == str_session
                                             select c).FirstOrDefault();

                            items_mat.id_estatus_material = 1;

                            data_mat.SaveChanges();
                        }

                        two_user = new int?[] { 1 };
                    }
                    catch
                    {
                        using (var data_mat = new db_transcriptEntities())
                        {
                            var items_mat = (from c in data_mat.inf_material
                                             where c.sesion == str_session
                                             select c).FirstOrDefault();

                            items_mat.id_estatus_material = 5;

                            data_mat.SaveChanges();
                        }
                    }
                    var videoInfo_mp4 = ffProbe.GetMediaInfo(str_file_save);

                    string str_duration_mp4 = videoInfo_mp4.Duration.Hours + ":" + videoInfo_mp4.Duration.Minutes + ":" + videoInfo_mp4.Duration.Seconds;

                    if (str_duration_wmv == str_duration_mp4)
                    {
                        File.Delete(str_file_save);
                    }
                    else
                    {
                        using (var data_mat = new db_transcriptEntities())
                        {
                            var items_mat = (from c in data_mat.inf_material
                                             where c.sesion == str_session
                                             select c).FirstOrDefault();

                            items_mat.id_estatus_material = 5;
                            data_mat.SaveChanges();
                        }
                    }
                }
            }
        }
Esempio n. 20
0
        public virtual void VideoStreamFromFileID(HttpContext context)
        {
            //System.Threading.Thread.Sleep(6000);
            YZRequest request = new YZRequest(context);
            string    fileId  = request.GetString("fileid");
            BPMObjectNameCollection supports = BPMObjectNameCollection.FromStringList(request.GetString("supports", null), ',');

            AttachmentInfo attachment;

            using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider)
            {
                using (IDbConnection cn = provider.OpenConnection())
                {
                    attachment = AttachmentManager.GetAttachmentInfo(provider, cn, fileId);
                }
            }

            string fileName     = attachment.Name;
            string fileExt      = attachment.Ext;
            string fileExtNoDot = fileExt == null ? "" : fileExt.TrimStart('.');
            long   fileSize     = attachment.Size;
            string filePath     = AttachmentInfo.FileIDToPath(fileId, AttachmentManager.AttachmentRootPath);

            if (!File.Exists(filePath))
            {
                throw new Exception(String.Format(Resources.YZStrings.Aspx_Upload_FileIDNotFount, fileId));
            }

            //有请求格式并且请求格式非元文件格式
            if (supports.Count != 0 && !supports.Contains(fileExtNoDot))
            {
                //发现已有转换文件
                string existFile = null;
                foreach (string format in supports)
                {
                    string outputFile = Path.Combine(Path.GetDirectoryName(filePath), String.Format("{0}.{1}", Path.GetFileNameWithoutExtension(filePath), format));
                    if (File.Exists(outputFile))
                    {
                        existFile = outputFile;
                        break;
                    }
                }

                if (!String.IsNullOrEmpty(existFile))
                {
                    filePath = existFile;
                }
                else
                {
                    //转换文件
                    string targetExt  = supports[0];
                    string outputFile = Path.Combine(Path.GetDirectoryName(filePath), String.Format("{0}.{1}", Path.GetFileNameWithoutExtension(filePath), targetExt));

                    var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                    ffMpeg.ConvertMedia(filePath, fileExtNoDot, outputFile, targetExt, null);
                    filePath = outputFile;
                }
            }

            this.ProcessResponseHeader(context, fileName, true);
            context.Response.TransmitFile(filePath);
        }
Esempio n. 21
0
        public HttpResponseMessage Get(string link, string size)
        {
            /*
             * Get the available video formats.
             * We'll work with them in the video and audio download examples.
             */
            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);

            //Create a stream for the file
            Stream stream = null;

            var fileName = AppDomain.CurrentDomain.BaseDirectory + "temp\\" + link.Split('=')[1] + DateTime.Now.ToFileTime();

            try
            {
                VideoInfo video = (size == "MP3")
                    ? videoInfos.First(info => info.Resolution <= 360)
                    : videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution <= 720);

                /*
                 * If the video has a decrypted signature, decipher it
                 */
                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }

                //This controls how many bytes to read at a time and send to the client
                int bytesToRead = 40960;

                // Buffer to read bytes in chunk size specified above
                byte[] buffer = new Byte[bytesToRead];

                // The number of bytes read
                //Create a WebRequest to get the file
                HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(video.DownloadUrl);

                //Create a response for this request
                HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

                if (fileReq.ContentLength > 0)
                {
                    fileResp.ContentLength = fileReq.ContentLength;
                }

                if (size == "MP3")
                {
                    WebClient client  = new WebClient();
                    string    address = video.DownloadUrl;
                    // Save the file to desktop for debugging
                    var loadedFileName = Path.Combine(fileName + ".mp4");
                    client.DownloadFile(address, loadedFileName);

                    var ffmpeg = new NReco.VideoConverter.FFMpegConverter();

                    ffmpeg.ConvertMedia(fileName + ".mp4"
                                        , fileName + ".mp3", "mp3");

                    ////Get the Stream returned from the response
                    stream = File.OpenRead(fileName + ".mp3");
                }
                else
                {
                    //Get the Stream returned from the response
                    stream = fileResp.GetResponseStream();
                }

                // prepare the response to the client. resp is the client Response
                var resp = HttpContext.Current.Response;

                if (size == "MP3")
                {
                    resp.ContentType = "audio/mp3";
                    //Name the file
                    resp.AddHeader("Content-Disposition", "attachment; filename=\"" + link.Split('=')[1] + ".mp3" + "\"");
                    resp.AddHeader("Content-Length", stream.Length.ToString());
                }
                else
                {
                    resp.ContentType = "video/mp4";
                    //Name the file
                    resp.AddHeader("Content-Disposition", "attachment; filename=\"" + link.Split('=')[1] + ".mp4" + "\"");
                    resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
                }


                int length;
                do
                {
                    // Verify that the client is connected.
                    if (resp.IsClientConnected)
                    {
                        // Read data into the buffer.
                        length = stream.Read(buffer, 0, bytesToRead);

                        // and write it out to the response's output stream
                        resp.OutputStream.Write(buffer, 0, length);

                        // Flush the data
                        resp.Flush();

                        //Clear the buffer
                        buffer = new Byte[bytesToRead];
                    }
                    else
                    {
                        // cancel the download if client has disconnected
                        length = -1;
                    }
                } while (length > 0); //Repeat until no data is read
                resp.Clear();
                resp.Redirect("http://" + HttpContext.Current.Request.Url.Authority + "/Home/YoutubeDownloader");
            }
            catch (Exception e)
            {
                //Return complete video
                HttpResponseMessage errorResponse = Request.CreateResponse(HttpStatusCode.OK);
                errorResponse.Content = new StringContent(e.StackTrace);
                //fullResponse.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4"); ;
                return(errorResponse);
            }
            finally
            {
                if (stream != null)
                {
                    //Close the input stream
                    stream.Close();
                }
                if (File.Exists(fileName + ".mp4"))
                {
                    File.Delete(fileName + ".mp4");
                }
                if (File.Exists(fileName + ".mp3"))
                {
                    File.Delete(fileName + ".mp3");
                }
            }
            //Return complete video
            //Here i need to redirect to a aspx page.
            //var response = Request.CreateResponse(HttpStatusCode.Moved);
            //response.Headers.Location = new Uri("http://" + HttpContext.Current.Request.Url.Authority + "/Home/FacebookDownloader");

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);

            //HttpResponseMessage fullResponse = Request.CreateResponse(HttpStatusCode.OK);
            ////fullResponse.Content = new StreamContent(stream);
            ////fullResponse.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4"); ;
            //return fullResponse;
        }
Esempio n. 22
0
/*        private VideoInfo getVideoLink(string link) {
 *          IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link,false);
 *          VideoInfo video;
 *          switch(preferType) {
 *              case FileType.AC3:
 *                  video = videoInfos.Where(info => info.VideoType == VideoType.Mp4 && info.AudioBitrate >= 192).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();
 *                  break;
 *              case FileType.AAC:
 *                  video = videoInfos.Where(info => info.AdaptiveType == AdaptiveType.Audio && info.AudioExtension.ToString().Equals(".aac", StringComparison.InvariantCultureIgnoreCase)).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();
 *                  break;
 *              case FileType.OGG:
 *                  video = videoInfos.Where(info => info.AdaptiveType == AdaptiveType.Audio && info.AudioExtension.ToString().Equals(".ogg", StringComparison.InvariantCultureIgnoreCase)).OrderByDescending(info => info.AudioBitrate).FirstOrDefault(); //.ogg - works
 *                  break;
 *              case FileType.MP3:
 *                  video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First();
 *                  break;
 *              default:
 *                  //video = videoInfos.Where(info => info.CanExtractAudio && info.AudioExtension.ToString().Equals("mp3",StringComparison.InvariantCultureIgnoreCase)).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();
 *                  video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();
 *                  break;
 *          }
 *
 *          //if (video == null)
 *          //{
 *              /*if (this.preferType != FileType.AAC)
 *              {
 *                  this.preferType = FileType.AAC;
 *                  ((Condenser)this.MdiParent).Invoke((MethodInvoker)delegate
 *                  {
 *                      ((Condenser)this.MdiParent).outputBox.AppendText("Failed to find preferred file type... trying .AAC" + Environment.NewLine +
 *                           this.link + Environment.NewLine + Environment.NewLine, Color.Orange);
 *                  });
 *                  video = videoInfos.Where(info => info.AdaptiveType == AdaptiveType.Audio && info.AudioExtension.ToString().Equals(".aac", StringComparison.InvariantCultureIgnoreCase)).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();
 *              }
 *          if (video == null)
 *          {
 *              if (this.preferType != FileType.MP3)
 *              {
 *                  this.preferType = FileType.MP3;
 *                  ((Condenser)this.MdiParent).Invoke((MethodInvoker)delegate
 *                  {
 *                      ((Condenser)this.MdiParent).outputBox.AppendText("Failed to find preferred file type... trying .MP3" + Environment.NewLine +
 *                          this.link + Environment.NewLine + Environment.NewLine, Color.Orange);
 *
 *                  });
 *                  video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();
 *                  /*if (video == null)
 *                  {
 *                      this.preferType = FileType.AC3;
 *                      ((Condenser)this.MdiParent).Invoke((MethodInvoker)delegate
 *                      {
 *                          ((Condenser)this.MdiParent).outputBox.AppendText("Failed to find preferred file type... pulling whatever I can!" + Environment.NewLine +
 *                              this.link + Environment.NewLine + Environment.NewLine, Color.Orange);
 *
 *                      });
 *                      video = videoInfos.Where(info => info.VideoType == VideoType.Mp4).OrderByDescending(info => info.Resolution).FirstOrDefault();
 *                  }
 *              }
 *          }
 *          //}
 *          return video;
 *      }*/

        private void download()
        {
            try
            {
                IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link, false);
                VideoInfo video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First();
                switch (this.preferType)
                {
                case FileType.AC3:
                    video = videoInfos.Where(info => info.VideoType == VideoType.Mp4 && info.AudioBitrate >= 192).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();
                    break;

                case FileType.AAC:
                    video = videoInfos.Where(info => info.AdaptiveType == AdaptiveType.Audio && info.AudioExtension.ToString().Equals(".aac", StringComparison.InvariantCultureIgnoreCase)).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();
                    break;

                case FileType.OGG:
                    video = videoInfos.Where(info => info.AdaptiveType == AdaptiveType.Audio && info.AudioExtension.ToString().Equals(".ogg", StringComparison.InvariantCultureIgnoreCase)).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();     //.ogg - works
                    break;

                case FileType.MP3:
                    video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();
                    break;

                default:
                    video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();
                    break;
                }

                if (video == null)
                {
                    if (this.preferType != FileType.MP3)
                    {
                        this.preferType = FileType.MP3;
                        ((Condenser)this.MdiParent).Invoke((MethodInvoker) delegate
                        {
                            ((Condenser)this.MdiParent).outputBox.AppendText("Failed to find preferred file type... trying .MP3" + Environment.NewLine +
                                                                             this.link + Environment.NewLine + Environment.NewLine, Color.Orange);
                        });
                        video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).FirstOrDefault();

                        /*if (video == null)
                         * {
                         *  this.preferType = FileType.AC3;
                         *  ((Condenser)this.MdiParent).Invoke((MethodInvoker)delegate
                         *  {
                         *      ((Condenser)this.MdiParent).outputBox.AppendText("Failed to find preferred file type... pulling whatever I can!" + Environment.NewLine +
                         *          this.link + Environment.NewLine + Environment.NewLine, Color.Orange);
                         *
                         *  });
                         *  video = videoInfos.Where(info => info.VideoType == VideoType.Mp4).OrderByDescending(info => info.Resolution).FirstOrDefault();
                         * }*/
                    }
                }

                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }
                var invalidChars  = System.IO.Path.GetInvalidFileNameChars();
                var validFileName = new String(video.Title.Where(x => !invalidChars.Contains(x)).ToArray());

                if (this.preferType != FileType.MP3)
                {
                    var audioDownloader = new VideoDownloader(video, path + validFileName + "." + video.AudioType.ToString().ToLower());
                    this.finalPath = path + validFileName + "." + video.AudioType.ToString().ToLower();
                    if (this.preferType == FileType.AC3)
                    {
                        audioDownloader = new VideoDownloader(video, path + validFileName + ".raindrop");// + video.AudioType.ToString().ToLower());
                        this.finalPath  = path + validFileName + ".raindrop";
                        if (File.Exists(path + validFileName + ".ac3"))
                        {
                            ((Condenser)this.MdiParent).Invoke((MethodInvoker) delegate
                            {
                                ((Condenser)this.MdiParent).outputBox.AppendText(validFileName + " is already in the bucket... skipping." + Environment.NewLine +
                                                                                 this.link + Environment.NewLine + Environment.NewLine, Color.Orange);
                            });
                            this.completed = true;
                            this.Invoke((MethodInvoker) delegate { this.Close(); /*this.completed = true;*/ });
                            return;
                        }
                    }

                    if (File.Exists(this.finalPath))
                    {
                        ((Condenser)this.MdiParent).Invoke((MethodInvoker) delegate
                        {
                            ((Condenser)this.MdiParent).outputBox.AppendText(validFileName + " is already in the bucket... skipping." + Environment.NewLine +
                                                                             this.link + Environment.NewLine + Environment.NewLine, Color.Orange);
                        });
                        this.completed = true;
                        this.Invoke((MethodInvoker) delegate { this.Close(); /*this.completed = true;*/ });
                        return;
                    }
                    //var audioDownloader = new VideoDownloader(video, path + validFileName + "." + video.AudioExtension);
                    //var audioDownloader = new VideoDownloader(video, path + validFileName + video.VideoExtension);
                    this.Invoke((MethodInvoker) delegate { this.Text = validFileName; });
                    //w.DownloadFile(video.DownloadUrl, path + validFileName + video.AudioExtension);
                    audioDownloader.DownloadProgressChanged += (thesender, args) => this.Invoke((MethodInvoker) delegate { this.progressBar1.Value = (int)(args.ProgressPercentage); });/* * 0.85*/
                    //audioDownloader.AudioExtractionProgressChanged += (thesender, args) => this.progressBar1.Value = (int)((args.ProgressPercentage * 0.15) + 85);
                    audioDownloader.Execute();
                    if (preferType == FileType.AC3)
                    {
                        var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                        this.Invoke((MethodInvoker) delegate { this.Text = "[Converting...] " + this.Text; });
                        //ffMpeg.ConvertProgress += (o, args) => this.Text = String.Format("Converting: {0} / {1}", args.Processed.ToString("mm:ss"), args.TotalDuration.ToString("mm:ss"));
                        ffMpeg.ConvertMedia(path + validFileName + ".raindrop", path + validFileName + ".ac3", "ac3");
                        try
                        {
                            File.Delete(path + validFileName + ".raindrop");
                        }
                        catch { }
                    }
                    this.completed = true;
                    ((Condenser)this.MdiParent).Invoke((MethodInvoker) delegate
                    {
                        ((Condenser)this.MdiParent).outputBox.AppendText(validFileName + " completed successfully." + Environment.NewLine +
                                                                         this.link + Environment.NewLine + Environment.NewLine, Color.Lime);
                    });
                }
                else
                {
                    var audioDownloader = new AudioDownloader(video, path + validFileName + video.AudioExtension);
                    this.finalPath = path + validFileName + "." + video.AudioExtension;
                    if (File.Exists(this.finalPath))
                    {
                        ((Condenser)this.MdiParent).Invoke((MethodInvoker) delegate
                        {
                            ((Condenser)this.MdiParent).outputBox.AppendText(validFileName + " is already in the bucket... skipping." + Environment.NewLine +
                                                                             this.link + Environment.NewLine + Environment.NewLine, Color.Orange);
                        });
                        this.completed = true;
                        this.Invoke((MethodInvoker) delegate { this.Close(); /*this.completed = true;*/ });
                        return;
                    }
                    this.Invoke((MethodInvoker) delegate { this.Text = validFileName; });
                    audioDownloader.DownloadProgressChanged        += (thesender, args) => this.progressBar1.Value = (int)(args.ProgressPercentage * 0.85);
                    audioDownloader.AudioExtractionProgressChanged += (thesender, args) => this.progressBar1.Value = (int)((args.ProgressPercentage * 0.15) + 85);
                    audioDownloader.Execute();
                    this.completed = true;
                    ((Condenser)this.MdiParent).Invoke((MethodInvoker) delegate
                    {
                        ((Condenser)this.MdiParent).outputBox.AppendText(validFileName + " completed successfully." + Environment.NewLine +
                                                                         this.link + Environment.NewLine + Environment.NewLine, Color.Lime);
                    });
                }
                this.Invoke((MethodInvoker) delegate { this.Close(); /*this.completed = true;*/ });
            }
            catch (Exception err)
            {
                if (!this.aborted)
                {
                    try
                    {
                        this.errored = true;
                        //if (!(err is InvalidOperationException))
                        //{
                        ((Condenser)this.MdiParent).Invoke((MethodInvoker) delegate
                        {
                            ((Condenser)this.MdiParent).outputBox.AppendText(this.link + " failed to condense." + Environment.NewLine +
                                                                             err.Message.ToString() + Environment.NewLine + Environment.NewLine, Color.Red);

                            /*((Condenser)this.MdiParent).outputBox.AppendText(this.link + " failed to condense." + Environment.NewLine +
                             *  err.ToString() + Environment.NewLine + Environment.NewLine, Color.Red);*/
                        });
                        //}
                        for (int x = 3; x > 0; x--)
                        {
                            string evaporate = "Failed to Condense [" + this.link + "]" + " Evaporating in " + x + " second";
                            evaporate += (x == 1) ? "" : "s";
                            evaporate += "...";
                            this.Invoke((MethodInvoker) delegate { this.Text = evaporate; });
                            Thread.Sleep(1000);
                        }
                        this.Invoke((MethodInvoker) delegate
                        {
                            this.Close();
                        });
                    }
                    catch { }
                }
            }
        }
Esempio n. 23
0
        void job(object sender, DoWorkEventArgs e)
        {
            // The sender is the BackgroundWorker object we need it to
            // report progress and check for cancellation.
            //NOTE : Never play with the UI thread here...
            CheckedListBox.CheckedItemCollection checklist = (CheckedListBox.CheckedItemCollection)e.Argument;
            foreach (object file in checklist)
            {
                string toPass = file.ToString();

                string dicomScan = toPass.Substring(toPass.LastIndexOf('|') + 1);

                string tempScanDirectory = sys.stillsPath + dicomScan + @"\";
                if (!Directory.Exists(tempScanDirectory))
                {
                    Directory.CreateDirectory(tempScanDirectory);
                }

                string pngTempDir = tempScanDirectory;


                var image  = new DicomImage(sys.dicomsPath + dicomScan);
                int frames = image.NumberOfFrames;

                // number format, making sure its prefixed with appropriate number of zeros
                // currently guarantees a four digit number
                // (dont think ive see dicom files with thousands of frames?)
                string fmt = "0000";

                for (int i = 0; i < frames; i++)
                {
                    // render each frame as a jpg
                    image.RenderImage(i).Save(pngTempDir + i.ToString(fmt) + ".png");

                    bgWorker.ReportProgress((int)i * 50 / frames);
                }

                int    fps     = 4;
                string outFile = sys.outPath + dicomScan.Replace(@"\", "");
                var    ffMpeg  = new NReco.VideoConverter.FFMpegConverter();
                var    outS    = new NReco.VideoConverter.ConvertSettings();
                outS.CustomInputArgs = "-framerate " + fps;
                outS.VideoFrameSize  = sys.convsettings["size"];

                ffMpeg.ConvertProgress += (o, args) => {
                    bgWorker.ReportProgress((int)(args.Processed.Seconds / (args.TotalDuration.Seconds * 100)));
                };


                // just need to make this less hardcoded
                ffMpeg.ConvertMedia(pngTempDir + @"%04d.png", "image2", outFile + @"." + sys.convsettings["format"], sys.convsettings["format"], outS);



                if (bgWorker.CancellationPending)
                {
                    // Set the e.Cancel flag so that the WorkerCompleted event
                    // knows that the process was cancelled.
                    e.Cancel = true;
                    bgWorker.ReportProgress(0);
                    return;
                }
            }

            //Report 100% completion on operation completed
            bgWorker.ReportProgress(100);
        }
Esempio n. 24
0
        void ConvertFileWithTextandWatermark(string file)
        {
            try
            {
                Font textBrush = new Font(textfont.SelectedItem.ToString(), (int)fontSize.Value);
                //first, create a dummy bitmap just to get a graphics object
                Image    img     = new Bitmap(1, 1);
                Graphics drawing = Graphics.FromImage(img);

                //measure the string to see how big the image needs to be
                SizeF textSize = drawing.MeasureString(OverlayText.Text.ToString(), textBrush);

                //free up the dummy image and old graphics object
                img.Dispose();
                drawing.Dispose();

                //create a new image of the right size
                img = new Bitmap((int)textSize.Width, (int)textSize.Height);

                drawing = Graphics.FromImage(img);

                //paint the background
                drawing.Clear(Color.Transparent);

                string     colorName    = textColour.SelectedItem.ToString();
                int        Transparency = TransparencySlider.Value;
                Color      newColor     = Color.FromArgb(Transparency, Color.FromName(colorName));
                SolidBrush brush        = new SolidBrush(newColor);

                drawing.DrawString(OverlayText.Text.ToString(), textBrush, brush, 0, 0);
                drawing.Save();

                img.Save(@"text.png", System.Drawing.Imaging.ImageFormat.Png);

                img.Dispose();
                textBrush.Dispose();
                drawing.Dispose();
                brush.Dispose();
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception error has occured:\n" + e.Message.ToString(), Title);
            }
            try
            {
                using (var srcImage = Image.FromFile(WatermarkFileChooser.FileName))
                {
                    var newWidth  = (int)(WatermarkXsize.Value);
                    var newHeight = (int)(WatermarkYsize.Value);
                    using (var newImage = new Bitmap(newWidth, newHeight))
                        using (var graphics = Graphics.FromImage(newImage))
                        {
                            graphics.SmoothingMode     = SmoothingMode.AntiAlias;
                            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                            graphics.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
                            newImage.Save(@"Resized.png", System.Drawing.Imaging.ImageFormat.Png);
                            newImage.Dispose();
                        }
                    srcImage.Dispose();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception error has occured:\n" + e.Message.ToString(), Title);
            }
            try
            {
                var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

                NReco.VideoConverter.FFMpegInput[] ffMpegInputs = new NReco.VideoConverter.FFMpegInput[] { new FFMpegInput(file), new FFMpegInput(@"Resized.png"), new FFMpegInput(@"text.png") };

                ConvertSettings csettings = new ConvertSettings();

                if (ResizeOptions.Enabled == true)
                {
                    csettings.SetVideoFrameSize((int)Xaxis.Value, (int)Yaxis.Value);
                }

                csettings.AudioCodec = "copy";
                //ffmpeg - i input - i logo1 - i logo2 - filter_complex 'overlay=x=10:y=H-h-10,overlay=x=W-w-10:y=H-h-10' output
                string arguement = "-filter_complex \"overlay=" + logoxaxis.Value.ToString() + ":" + logoyaxis.Value.ToString() + ",overlay=" + textxaxis.Value.ToString() + ":" + textyaxis.Value.ToString() + "\"";

                csettings.CustomOutputArgs = arguement;


                if (FormatChooser.SelectedIndex == 0)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.avi", Format.avi, csettings);
                }
                else if (FormatChooser.SelectedIndex == 1)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mp4", Format.mp4, csettings);
                }
                else if (FormatChooser.SelectedIndex == 2)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mv4", Format.m4v, csettings);
                }
                else if (FormatChooser.SelectedIndex == 3)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.gif", Format.gif, csettings);
                }
                else if (FormatChooser.SelectedIndex == 4)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mov", Format.mov, csettings);
                }
                else if (FormatChooser.SelectedIndex == 5)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.wmv", Format.wmv, csettings);
                }
                else if (FormatChooser.SelectedIndex == 6)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.swf", Format.swf, csettings);
                }
                else if (FormatChooser.SelectedIndex == 7)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.ogg", Format.ogg, csettings);
                }
                else if (FormatChooser.SelectedIndex == 8)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mpeg", Format.mpeg, csettings);
                }
                else //Nothing selected? Default to .avi format.
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.avi", Format.avi, csettings);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception error has occured:\n" + e.Message.ToString(), Title);
            }
        }
Esempio n. 25
0
        void ConvertFileWithTextOverlayOnly(string file)
        {
            try
            {
                Font textBrush = new Font(textfont.SelectedItem.ToString(), (int)fontSize.Value);
                //first, create a dummy bitmap just to get a graphics object
                Image    img     = new Bitmap(1, 1);
                Graphics drawing = Graphics.FromImage(img);

                //measure the string to see how big the image needs to be
                SizeF textSize = drawing.MeasureString(OverlayText.Text.ToString(), textBrush);

                //free up the dummy image and old graphics object
                img.Dispose();
                drawing.Dispose();

                //create a new image of the right size
                img = new Bitmap((int)textSize.Width, (int)textSize.Height);

                drawing = Graphics.FromImage(img);

                //paint the background
                drawing.Clear(Color.Transparent);

                string     colorName    = textColour.SelectedItem.ToString();
                int        Transparency = TransparencySlider.Value;
                Color      newColor     = Color.FromArgb(Transparency, Color.FromName(colorName));
                SolidBrush brush        = new SolidBrush(newColor);

                drawing.DrawString(OverlayText.Text.ToString(), textBrush, brush, 0, 0);
                drawing.Save();

                img.Save(@"text.png", System.Drawing.Imaging.ImageFormat.Png);

                textBrush.Dispose();
                drawing.Dispose();
                img.Dispose();
                brush.Dispose();
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception error has occured:\n" + e.Message.ToString(), Title);
            }
            try
            {
                var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

                NReco.VideoConverter.FFMpegInput[] ffMpegInputs = new NReco.VideoConverter.FFMpegInput[] { new FFMpegInput(file), new FFMpegInput(@"text.png") };

                ConvertSettings csettings = new ConvertSettings();

                if (ResizeOptions.Enabled == true)
                {
                    csettings.SetVideoFrameSize((int)Xaxis.Value, (int)Yaxis.Value);
                }

                csettings.AudioCodec = "copy";
                string arguement = "-filter_complex \"overlay=" + textxaxis.Value.ToString() + ":" + textyaxis.Value.ToString() + "\"";

                csettings.CustomOutputArgs = arguement;


                if (FormatChooser.SelectedIndex == 0)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.avi", Format.avi, csettings);
                }
                else if (FormatChooser.SelectedIndex == 1)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mp4", Format.mp4, csettings);
                }
                else if (FormatChooser.SelectedIndex == 2)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mv4", Format.m4v, csettings);
                }
                else if (FormatChooser.SelectedIndex == 3)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.gif", Format.gif, csettings);
                }
                else if (FormatChooser.SelectedIndex == 4)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mov", Format.mov, csettings);
                }
                else if (FormatChooser.SelectedIndex == 5)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.wmv", Format.wmv, csettings);
                }
                else if (FormatChooser.SelectedIndex == 6)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.swf", Format.swf, csettings);
                }
                else if (FormatChooser.SelectedIndex == 7)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.ogg", Format.ogg, csettings);
                }
                else if (FormatChooser.SelectedIndex == 8)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mpeg", Format.mpeg, csettings);
                }
                else //Nothing selected? Default to .avi format.
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.avi", Format.avi, csettings);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception error has occured:\n" + e.Message.ToString(), Title);
            }
        }
Esempio n. 26
0
        void ConvertFileWithWatermarkOnly(string file)
        {
            try
            {
                using (var srcImage = Image.FromFile(WatermarkFileChooser.FileName))
                {
                    var newWidth  = (int)(WatermarkXsize.Value);
                    var newHeight = (int)(WatermarkYsize.Value);
                    using (var newImage = new Bitmap(newWidth, newHeight))
                        using (var graphics = Graphics.FromImage(newImage))
                        {
                            graphics.SmoothingMode     = SmoothingMode.AntiAlias;
                            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                            graphics.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
                            newImage.Save(@"Resized.png", System.Drawing.Imaging.ImageFormat.Png);
                            newImage.Dispose();
                        }
                    srcImage.Dispose();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception error has occured:\n" + e.Message.ToString(), Title);
            }
            try
            {
                var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

                NReco.VideoConverter.FFMpegInput[] ffMpegInputs = new NReco.VideoConverter.FFMpegInput[] { new FFMpegInput(file), new FFMpegInput(@"Resized.png") };

                ConvertSettings csettings = new ConvertSettings();

                if (ResizeOptions.Enabled == true)
                {
                    csettings.SetVideoFrameSize((int)Xaxis.Value, (int)Yaxis.Value);
                }

                csettings.AudioCodec = "copy";
                string arguement = "-filter_complex \"overlay=" + logoxaxis.Value.ToString() + ":" + logoyaxis.Value.ToString() + "\"";

                csettings.CustomOutputArgs = arguement;


                if (FormatChooser.SelectedIndex == 0)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.avi", Format.avi, csettings);
                }
                else if (FormatChooser.SelectedIndex == 1)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mp4", Format.mp4, csettings);
                }
                else if (FormatChooser.SelectedIndex == 2)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mv4", Format.m4v, csettings);
                }
                else if (FormatChooser.SelectedIndex == 3)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.gif", Format.gif, csettings);
                }
                else if (FormatChooser.SelectedIndex == 4)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mov", Format.mov, csettings);
                }
                else if (FormatChooser.SelectedIndex == 5)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.wmv", Format.wmv, csettings);
                }
                else if (FormatChooser.SelectedIndex == 6)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.swf", Format.swf, csettings);
                }
                else if (FormatChooser.SelectedIndex == 7)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.ogg", Format.ogg, csettings);
                }
                else if (FormatChooser.SelectedIndex == 8)
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.mpeg", Format.mpeg, csettings);
                }
                else //Nothing selected? Default to .avi format.
                {
                    ffMpeg.ConvertMedia(ffMpegInputs, file + "ConvertedWithWatermark.avi", Format.avi, csettings);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception error has occured:\n" + e.Message.ToString(), Title);
            }
        }
Esempio n. 27
0
        static void Main(string[] args)
        {
            try
            {
                if (config.Length == 0)
                {
                    writeConfig();
                }
                readConfig();
                writeConfig();
                if (defaultConfig.HLAPath.EndsWith(@"\"))
                {
                    restOfPath = @"game\hlvr\panorama\videos";
                }
            }
            catch
            {
                hasErrored = true;
                Console.WriteLine("There was an error with your config. Try editing the config again, or delete it and let it re-generate.");
            }
            if (!hasErrored)
            {
                System.IO.Directory.CreateDirectory(@".\put WebMs Here");
                System.IO.Directory.CreateDirectory(@".\put GIFs Here");
                string[] files    = Directory.GetFiles(@".\put WebMs Here", @"*.webm");
                string[] files4   = Directory.GetFiles(@".\put GIFs Here", @"*.gif");
                string[] files5   = Directory.GetFiles(@".\put GIFs Here", @"*.mp4");
                string   fullPath = defaultConfig.HLAPath + restOfPath;
                if (files.Length == 0 && files4.Length == 0)
                {
                    Console.WriteLine("Put your webms in the folder called \"put WebMs Here\" \nor put gifs in the folder called \"put GIFs Here\" \nthen run the program again.");
                    hasWebMs = false;
                }
                if (!Directory.Exists(fullPath))
                {
                    Console.WriteLine("Check the HLAPath, the path doesn't seem to exist.");
                    hasWebMs = false;
                }
                var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

                foreach (var fil in files4)
                {
                    string fName = fil.Substring(@".\put GIFs Here".Length + 1);
                    ffMpeg.ConvertMedia(fil, fName + ".webm", Format.webm);
                    File.Delete(fil);
                }
                foreach (var fil in files5)
                {
                    string fName = fil.Substring(@".\put GIFs Here".Length + 1);
                    ffMpeg.ConvertMedia(fil, fName + ".webm", Format.webm);
                    File.Delete(fil);
                }

                files4 = Directory.GetFiles(@".\", @"*.webm");
                foreach (var fil in files4)
                {
                    string fName = fil.Substring(@".\".Length);
                    File.Move(fil, @".\put WebMs Here\" + fName);
                }

                files = Directory.GetFiles(@".\put WebMs Here", @"*.webm");
                System.IO.Directory.CreateDirectory(@".\Backup Files");

                string[] files2 = Directory.GetFiles(fullPath, "*.webm");
                string[] files3 = Directory.GetFiles(@".\Backup Files");

                do
                {
                    if (hasWebMs)
                    {
                        if (files3.Length == 0)
                        {
                            foreach (var file in files2)
                            {
                                string fName = file.Substring(fullPath.Length + 1);

                                File.Copy(Path.Combine(fullPath, fName), @".\Backup Files\" + fName);
                            }
                        }
                        Random rand = new Random();

                        File.Copy(files[rand.Next(files.Length)], Path.Combine(fullPath, file1), true);
                        File.Copy(files[rand.Next(files.Length)], Path.Combine(fullPath, file2), true);
                        File.Copy(files[rand.Next(files.Length)], Path.Combine(fullPath, file3), true);
                        File.Copy(files[rand.Next(files.Length)], Path.Combine(fullPath, file4), true);
                        File.Copy(files[rand.Next(files.Length)], Path.Combine(fullPath, file5), true);
                        File.Copy(files[rand.Next(files.Length)], Path.Combine(fullPath, file6), true);
                        File.Copy(files[rand.Next(files.Length)], Path.Combine(fullPath, file7), true);
                        File.Copy(files[rand.Next(files.Length)], Path.Combine(fullPath, file8), true);
                        Console.WriteLine("Operation Successful");
                    }

                    if (defaultConfig.loop)
                    {
                        Thread.Sleep(180000);
                    }
                } while (defaultConfig.loop);
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Esempio n. 28
0
 private void button3_Click(object sender, EventArgs e)
 {
     try
     {
         if (comboBox1.SelectedItem == ".ac3")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.ac3", Format.ac3);
         }
         if (comboBox1.SelectedItem == ".aiff")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.aiff", Format.aiff);
         }
         if (comboBox1.SelectedItem == ".alaw")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.alaw", Format.alaw);
         }
         if (comboBox1.SelectedItem == ".asf")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.asf", Format.asf);
         }
         if (comboBox1.SelectedItem == ".ast")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.ast", Format.ast);
         }
         if (comboBox1.SelectedItem == ".au")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.au", Format.au);
         }
         if (comboBox1.SelectedItem == ".avi")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.avi", Format.avi);
         }
         if (comboBox1.SelectedItem == ".vaf")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.caf", Format.caf);
         }
         if (comboBox1.SelectedItem == ".dts")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.dts", Format.dts);
         }
         if (comboBox1.SelectedItem == ".eac3")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.eac3", Format.eac3);
         }
         if (comboBox1.SelectedItem == ".ffm")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.ffm", Format.ffm);
         }
         if (comboBox1.SelectedItem == ".flac")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.flac", Format.flac);
         }
         if (comboBox1.SelectedItem == ".flv")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.flv", Format.flv);
         }
         if (comboBox1.SelectedItem == ".gif")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.gif", Format.gif);
         }
         if (comboBox1.SelectedItem == ".m4v")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.m4v", Format.m4v);
         }
         if (comboBox1.SelectedItem == ".matroska")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.matroska", Format.matroska);
         }
         if (comboBox1.SelectedItem == ".mjpeg")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.mjpeg", Format.mjpeg);
         }
         if (comboBox1.SelectedItem == ".mov")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.mov", Format.mov);
         }
         if (comboBox1.SelectedItem == ".mp4")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.mp4", Format.mp4);
         }
         if (comboBox1.SelectedItem == ".mpeg")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.mpeg", Format.mpeg);
         }
         if (comboBox1.SelectedItem == ".mulaw")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.mulaw", Format.mulaw);
         }
         if (comboBox1.SelectedItem == ".ogg")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.ogg", Format.ogg);
         }
         if (comboBox1.SelectedItem == ".oma")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.oma", Format.oma);
         }
         if (comboBox1.SelectedItem == ".rm")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.rm", Format.rm);
         }
         if (comboBox1.SelectedItem == ".swf")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.swf", Format.swf);
         }
         if (comboBox1.SelectedItem == ".webm")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.webm", Format.webm);
         }
         if (comboBox1.SelectedItem == ".wmv")
         {
             var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
             ffMpeg.ConvertMedia(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName) + " - Converted by .NET Converter.wmv", Format.wmv);
         }
     }
     catch (Exception error)
     {
         MessageBox.Show(error.ToString(), error.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
         Application.Exit();
     }
 }
        public void ExportVideo(ProgressDialogController progress)
        {
            string inputFile = @Manager.Match.VideoFile;
            string videoName = Manager.Match.VideoFile.Split('\\').Last();

            videoName = videoName.Split('.').First();
            Directory.CreateDirectory(@Location);
            string collectionName = @Location + @"\" + Manager.ActivePlaylist.Name + "_collection.mp4";
            int    rallyCount     = Manager.ActivePlaylist.Rallies.Count();
            int    sum            = 0;

            for (int s = 1; s <= rallyCount; s++)
            {
                sum = sum + s;
            }
            if (rallyCollection)
            {
                progressBar = sum * 2;
            }
            else
            {
                progressBar = sum;
            }

            currentProgress = 0;

            string[] RallyCollection = new string[rallyCount];
            string[] ConcatRally     = new string[2];
            progress.Minimum = 0;
            progress.Maximum = progressBar;
            progress.SetProgress(0);

            for (int i = 0; i < rallyCount; i++)
            {
                progress.SetMessage("Export Playlist '" + Manager.ActivePlaylist.Name + "': \n\nRally " + (i + 1) + " is being created...");
                Rally  curRally    = Manager.ActivePlaylist.Rallies[i];
                string RallyNumber = curRally.Number.ToString();
                string RallyScore  = curRally.CurrentRallyScore.ToString();
                RallyScore = RallyScore.Replace(":", "-");
                string SetScore = curRally.CurrentSetScore.ToString();
                SetScore = SetScore.Replace(":", "-");
                string fileName = @Location + @"\#" + RallyNumber + "_" + RallyScore + " (" + SetScore + ").mp4";
                RallyCollection[i] = fileName;

                var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

                NReco.VideoConverter.ConvertSettings settings = new NReco.VideoConverter.ConvertSettings()
                {
                    Seek        = Convert.ToSingle(curRally.Start / 1000),
                    MaxDuration = Convert.ToSingle((curRally.End - curRally.Start) / 1000),
                    //VideoFrameSize = NReco.VideoConverter.FrameSize.hd720,
                    AudioCodec = "copy", VideoCodec = "copy"
                };
                ffMpeg.ConvertMedia(@Manager.Match.VideoFile, null, fileName, null, settings);


                currentProgress = currentProgress + (i + 1);
                progress.SetProgress(currentProgress);
            }

            if (rallyCollection)
            {
                progress.SetMessage("\n Collection is currently being created! \n\nIt may take a while...");
                var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                ffMpeg.ConvertProgress += UpdateProgress;

                NReco.VideoConverter.ConcatSettings settings = new NReco.VideoConverter.ConcatSettings();
                ffMpeg.ConcatMedia(RallyCollection, @Location + @"\" + Manager.ActivePlaylist.Name + "_collection(" + rallyCount + ").mp4", NReco.VideoConverter.Format.mp4, settings);
                progress.SetProgress(progressBar);
            }

            if (!singleRallies)
            {
                for (int i = 0; i < rallyCount; i++)
                {
                    File.Delete(RallyCollection[i]);
                }
            }
        }
Esempio n. 30
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message != null)
            {
                Telegram.Bot.Types.Message message = e.Message;
                Console.WriteLine($"Received a message from {message.Chat.FirstName} at {message.Date}. It says: \"{e.Message.Text}\"");

                switch (message.Text)
                {
                case "/stop":
                    step = -1;
                    break;

                case "/start":

                    await bot.SendTextMessageAsync(
                        chatId : message.Chat,
                        text : "Send link",
                        replyToMessageId : message.MessageId
                        );

                    step = 0;
                    break;

                default:
                    if (step == 0)
                    {
                        link = message.Text;

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send title",
                            replyToMessageId : message.MessageId
                            );

                        step = 1;

                        try
                        {
                            string id = YoutubeClient.ParseVideoId(link);

                            MediaStreamInfoSet streamInfoSet = await clientYT.GetVideoMediaStreamInfosAsync(id);     //So54Khf7bB8

                            video = await clientYT.GetVideoAsync(id);

                            duration = video.Duration;     // 00:07:14
                            AudioStreamInfo streamInfo = streamInfoSet.Audio.OrderBy(s => s.Bitrate).First();
                            string          ext        = streamInfo.Container.GetFileExtension();

                            Console.WriteLine("Downloading audio");

                            await clientYT.DownloadMediaStreamAsync(streamInfo, $"Audio\\audio.{ext}");

                            Console.WriteLine("Audio has been downloaded. Converting audio");

                            FFMpegConverter convertAudio = new NReco.VideoConverter.FFMpegConverter();
                            convertAudio.ConvertMedia($"Audio\\audio.{ext}", null, "Audio\\audio.ogg", null, new ConvertSettings()
                            {
                                //CustomOutputArgs = $"-b:a {streamInfo.Bitrate}"
                                CustomOutputArgs = $"-c:a libopus -b:a {streamInfo.Bitrate}"
                            });

                            Console.WriteLine("Converting has been completed.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                            await bot.SendTextMessageAsync(
                                chatId : message.Chat,
                                text : "The link that you have sent is not valid or the file size is too big. Please, send it again",
                                replyToMessageId : message.MessageId
                                );

                            step = 0;
                        }
                    }
                    else if (step == 1)
                    {
                        title    = message.Text.ToUpper();
                        titleLen = title.Length - 27;

                        output = $"<b>{message.Text}</b>\n";

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send author",
                            replyToMessageId : message.MessageId
                            );

                        step = 2;
                    }
                    else if (step == 2)
                    {
                        author    = message.Text.ToUpper();
                        authorLen = author.Length - 14;

                        output += $"{message.Text}\n\n";

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send desription",
                            replyToMessageId : message.MessageId
                            );

                        step = 3;
                    }
                    else if (step == 3)
                    {
                        output += $"{message.Text}\n\n";

                        ReplyKeyboardMarkup replyKeyboardMarkup = new[]
                        {
                            new[] { "Бизнес", "Биография", "Психология", "Саморазвитие" },
                            new[] { "Философия", "Наука", "История", "Финансы" }
                        };

                        replyKeyboardMarkup.OneTimeKeyboard = true;

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send genre",
                            replyToMessageId : message.MessageId,
                            replyMarkup : replyKeyboardMarkup
                            );

                        output += $"🔈 <b>Продолжительность ≈</b> {Math.Round(duration.TotalMinutes, MidpointRounding.AwayFromZero)} минут\n";

                        step = 4;
                    }
                    else if (step == 4)
                    {
                        genre   = message.Text.ToUpper();
                        output += $"📝 <b>Жанр:</b> #{message.Text}";

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send image",
                            replyToMessageId : message.MessageId
                            );

                        step = 5;
                    }
                    else if (step == 5)
                    {
                        if (message.Type == MessageType.Photo)
                        {
                            FileStream fs = System.IO.File.OpenWrite("Image\\cover.png");
                            await bot.GetInfoAndDownloadFileAsync(message.Photo.Last().FileId, fs);

                            fs.Close();

                            await bot.SendTextMessageAsync(
                                chatId : message.Chat,
                                text : "Cover image received",
                                replyToMessageId : message.MessageId
                                );

                            FileStream pltrFile = File.OpenRead("Image\\palitre.png");

                            await bot.SendPhotoAsync(
                                chatId : message.Chat,
                                photo : pltrFile,
                                caption : "Choose your colors. First, send me primary color",
                                replyMarkup : replyKeyboardMarkupColor
                                );

                            pltrFile.Close();
                            step = 6;
                        }
                        else
                        {
                            await bot.SendTextMessageAsync(message.Chat, "I implores you to send photo and not anything else, capish?");

                            step = 5;
                        }
                    }
                    else if (step == 6)
                    {
                        if (message.Text[0] == '#')
                        {
                            primColor = message.Text;
                        }
                        else
                        {
                            primColor = '#' + message.Text;
                        }
                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "I have got primary color. Now, send me secondary color"
                            );

                        step = 7;
                    }
                    else if (step == 7)
                    {
                        if (message.Text[0] == '#')
                        {
                            secColor = message.Text;
                        }
                        else
                        {
                            secColor = '#' + message.Text;
                        }

                        replyKeyboardMarkupColor.OneTimeKeyboard = true;
                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "I have got secondary color. Now, send me background color",
                            replyMarkup : replyKeyboardMarkupColor
                            );

                        step = 8;
                    }
                    else if (step == 8)
                    {
                        if (message.Text[0] == '#')
                        {
                            backColor = message.Text;
                        }
                        else
                        {
                            backColor = '#' + message.Text;
                        }



                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "I have got background color. Now, I will send you a final post"
                            );

                        if (authorLen > 0)
                        {
                            authorFontSize -= authorLen * 8;
                        }
                        if (titleLen > 0)
                        {
                            titleFontSize -= titleLen * 5;
                        }

                        using (MagickImage form = new MagickImage(MagickColors.White, 1920, 1080))
                        {
                            new Drawables()

                            //Draw rectangle
                            .FillColor(new MagickColor(backColor))
                            .Rectangle(0, 0, 840, 1080)

                            //Draw hashtag
                            .FontPointSize(100)
                            .Font("Font\\nrwstr.otf")
                            .FillColor(new MagickColor(secColor))
                            .Text(30, 124, "#")

                            //Draw genre
                            .Font("Font\\amcap.ttf")
                            .Text(124, 124, genre)

                            //Draw title
                            .FontPointSize(titleFontSize)
                            .FillColor(new MagickColor(primColor))
                            .Text(30, 520, title)

                            //Draw name of the author
                            .FontPointSize(authorFontSize)
                            .FillColor(new MagickColor(secColor))
                            .Text(30, 650, author)

                            //Draw name of the channel
                            .FillColor(new MagickColor(primColor))
                            .FontPointSize(50)
                            .Text(150, 960, "THINK! - АУДИОПОДКАСТЫ")

                            //Draw link of the channel
                            .Font("Font\\nrwstr.otf")
                            .FillColor(new MagickColor(secColor))
                            .FontPointSize(40)
                            .Text(150, 1010, "T.ME/THINKAUDIO")

                            .Draw(form);

                            using MagickImage cover = new MagickImage("Image\\cover.png");
                            cover.Resize(1280, 1280);
                            form.Composite(cover, 840, 0, CompositeOperator.Over);

                            //Draw logo of the channel
                            using MagickImage logo = new MagickImage("Image\\logo.png");
                            logo.Alpha(AlphaOption.Set);
                            logo.ColorFuzz = new Percentage(0);
                            logo.Settings.BackgroundColor = MagickColors.Transparent;
                            //logo.Settings.FillColor = MagickColors.White;
                            logo.Opaque(MagickColors.White, new MagickColor(primColor));
                            form.Composite(logo, 30, 920, CompositeOperator.Over);

                            form.Write("Image\\template.png");
                        }

                        await bot.SendTextMessageAsync(message.Chat, "Template has been created. Sending it to you");

                        using (var stream = new FileStream("Image\\template.png", FileMode.Open))
                        {
                            InputOnlineFile inputOnlineFile = new InputOnlineFile(stream, "template.png");
                            await bot.SendDocumentAsync(message.Chat, inputOnlineFile);
                        }


                        try
                        {
                            ImgurClient   client   = new ImgurClient("", "");
                            ImageEndpoint endpoint = new ImageEndpoint(client);
                            IImage        image;
                            using (FileStream fs = new FileStream("Image\\template.png", FileMode.Open))
                            {
                                await bot.SendTextMessageAsync(message.Chat, "Uploading Image to Imgur");

                                image = await endpoint.UploadImageStreamAsync(fs);
                            }
                            picLink = image.Link;
                            Console.WriteLine("Image uploaded. Image Url: " + image.Link);

                            output += $"<a href=\"{picLink}\">&#8205;</a>";

                            await bot.SendTextMessageAsync(
                                chatId : message.Chat,
                                text : output,
                                parseMode : ParseMode.Html
                                );
                        }
                        catch (ImgurException imgurEx)
                        {
                            Debug.Write("An error occurred uploading an image to Imgur.");
                            Debug.Write(imgurEx.Message);
                        }

                        using (var stream = new FileStream("Audio\\audio.ogg", FileMode.Open))
                        {
                            await bot.SendVoiceAsync(
                                chatId : message.Chat,
                                voice : stream

                                );
                        }
                        step = -1;
                    }
                    break;
                }
            }
        }
        private List<Bitmap> readVideoAsImages_AForge(string filePathToOpen)
        {
            FileStream F = new FileStream("sample.txt", FileMode.CreateNew, FileAccess.Write, FileShare.Write);

            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
            ffMpeg.ConvertMedia(filePathToOpen, F, NReco.VideoConverter.Format.avi);

            return new List<Bitmap>();
        }