private FastBitmap GetBitmap(float time, MemoryStream stream)
 {
     FastBitmap result = null;
     var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
     ffMpeg.GetVideoThumbnail(FilePath, stream, time);
     if (stream.Length != 0)
     {
         Image img = Image.FromStream(stream);
         result = new FastBitmap(new Bitmap(img, img.Width/Scale , img.Height/Scale));
     }
     return result;
 }
Beispiel #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);
            }
        }
Beispiel #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();
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to the Realtime Audio Transcriber");
            audioProcesser = new AudioProcessor();
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.LogLevel     = "verbose";
            ffMpeg.LogReceived += logs;
            outputStream        = new MemoryStream();
            Console.WriteLine("Created FFMPeg");
            string streamUrl = "testing_file.mp3";

            audioProcesser.AudioStart();
            var vidtask = ffMpeg.ConvertLiveMedia(streamUrl, null, outputStream, "wav", new ConvertSettings
            {
                CustomOutputArgs = "-vn -r 25 -c:a pcm_s16le -b:a 16k -ac 1 -ar 16000"
            });

            vidtask.OutputDataReceived += DataReceived;
            Console.WriteLine("Starting");
            vidtask.Start();
            Console.WriteLine("Started");
            vidtask.Wait();
            byte[] buffer = new byte[2048]; // using 2kB byte arrays
            int    bytesRead;

            Console.Read();
            //connection.Stop();
            Console.WriteLine("Complete");
        }
        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());
        }
Beispiel #6
0
        /// <summary>
        /// だいたい0.3秒おきの動画サムネイルを取得する
        /// </summary>
        /// <param name="videoPath">ビデオファイルパス</param>
        /// <returns></returns>
        public static IEnumerable <Bitmap> GetThumbnails(string videoPath)
        {
            // メタ情報で再生時間取得
            var ffprob   = new NReco.VideoInfo.FFProbe();
            var info     = ffprob.GetMediaInfo(videoPath);
            var duration = info.Duration;

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

            // 最短0.3秒おき、最大100分割
            var skipSec = duration.TotalSeconds < 30 ?
                          0.3f : (float)(duration.TotalSeconds / 100);

            var frameSec = 0f;

            while ((float)duration.TotalSeconds > frameSec)
            {
                // Bitmapリソースは受信側で開放する。
                var jpegStream = new MemoryStream();
                videoConv.GetVideoThumbnail(videoPath, jpegStream, frameSec);
                yield return((Bitmap)Image.FromStream(jpegStream));

                frameSec += skipSec;
            }
        }
Beispiel #7
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;
        }
Beispiel #8
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);
            }
        }
Beispiel #9
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);
        }
Beispiel #10
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);
        }
Beispiel #11
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);
        }
Beispiel #12
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);
        }
        /*
         * Listener for the Open button
         * Used to get a frame from the video in the given in FilePath
         * and set it as the thumbnail on the form
         */
        private void Open_Click(object sender, EventArgs e)
        {
            //get thumbnail from video and save it as a jpg
            string path   = FilePath.Text.ToString();
            var    ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            ffMpeg.GetVideoThumbnail(path, "thumbnails/thumbnail.jpg", 1);

            //set the picturebox to the thumbnail image
            Thumbnail_Box.SizeMode = PictureBoxSizeMode.StretchImage;
            Thumbnail_Box.Image    = new Bitmap("thumbnails/thumbnail.jpg");
        }
Beispiel #14
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());
        }
Beispiel #15
0
        // Get the bitmap representing a video file
        // Note that displayIntent is ignored as it's specific to interaction with WCF's bitmap cache, which doesn't occur in rendering video preview frames
        public static BitmapSource GetBitmapFromVideoFile(string filePath, Nullable <int> desiredWidthOrHeight, ImageDisplayIntentEnum displayIntent, ImageDimensionEnum imageDimension, out bool isCorruptOrMissing)
        {
            if (!System.IO.File.Exists(filePath))
            {
                isCorruptOrMissing = true;
                return(Constant.ImageValues.FileNoLongerAvailable.Value);
            }
            // Our FFMPEG installation is the 64 bit version. In case someone is using a 32 bit machine, we use the MediaEncoder instead.
            if (Environment.Is64BitOperatingSystem == false)
            {
                // System.Diagnostics.Debug.Print("Can't use ffmpeg as this is a 32 bit machine. Using MediaEncoder instead");
                return(BitmapUtilities.GetVideoBitmapFromFileUsingMediaEncoder(filePath, desiredWidthOrHeight, displayIntent, imageDimension, out isCorruptOrMissing));
            }
            try
            {
                //Saul TO DO:
                // Note: not sure of the cost of creating a new converter every time. May be better to reuse it?
                Stream          outputBitmapAsStream = new MemoryStream();
                FFMpegConverter ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                ffMpeg.GetVideoThumbnail(filePath, outputBitmapAsStream);

                // Scale the video to the desired dimension
                outputBitmapAsStream.Position = 0;
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                if (desiredWidthOrHeight != null)
                {
                    if (imageDimension == ImageDimensionEnum.UseWidth)
                    {
                        bitmap.DecodePixelWidth = desiredWidthOrHeight.Value;
                    }
                    else
                    {
                        bitmap.DecodePixelHeight = desiredWidthOrHeight.Value;
                    }
                }
                bitmap.CacheOption  = BitmapCacheOption.None;
                bitmap.StreamSource = outputBitmapAsStream;
                bitmap.EndInit();
                bitmap.Freeze();
                isCorruptOrMissing = false;
                return(bitmap);
            }
            catch // (FFMpegException e)
            {
                // Couldn't get the thumbnail using FFMPEG. Fallback to try getting it using the MediaEncoder
                return(GetVideoBitmapFromFileUsingMediaEncoder(filePath, desiredWidthOrHeight, displayIntent, imageDimension, out isCorruptOrMissing));
                // We don't print the exception // (Exception exception)
                // TraceDebug.PrintMessage(String.Format("VideoRow/LoadBitmap: Loading of {0} failed in Video - LoadBitmap. {0}", imageFolderPath));
            }
        }
Beispiel #16
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";
        }
Beispiel #17
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

            NReco.VideoConverter.ConcatSettings set = new NReco.VideoConverter.ConcatSettings();
            set.SetVideoFrameSize(640, 480);
            set.ConcatAudioStream = false;
            set.ConcatVideoStream = true;
            //set.CustomOutputArgs = "-filter_complex '[0:v] setsar=sar=1 [in1]; [1:v] setsar=sar=1 [in2]; [in1][in2] concat [v]; [0:a][1:a] concat=v=0:a=1 [a]' -map '[v]' -map '[a]'";
            //set.CustomOutputArgs = "-filter_complex \"[0:0] setsar=1/1[sarfix];[sarfix] [0:1] [1:0] [1:1] concat=n=2:v=1:a=1 [v] [a] \" -map \"[v]\" -map \"[a]\"";
            string[] inputfiles = { "opening.mp4", tempout };
            ffMpeg.ConcatMedia(inputfiles, output, NReco.VideoConverter.Format.mp4, set);
            MessageBox.Show("FINISHED");
        }
        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;
        }
Beispiel #19
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");
        }
Beispiel #20
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");
            }
        }
Beispiel #21
0
        private void ChooseVidBtn_Click(object sender, EventArgs e)
        {
            PreviewImg.SetLength(0);
            PreviewImg.Position       = 0;
            VideoFileChooser.Filter   = "Video File|*.avi;*.mpeg;*.flv;*.mov;*.ogg;*.mp4;*.wmv;*.mkv;*.h264";
            VideoFileChooser.FileName = "";
            DialogResult result = VideoFileChooser.ShowDialog();

            if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(VideoFileChooser.FileName))
            {
                var ffMpeg      = new NReco.VideoConverter.FFMpegConverter();
                var ffMpegInput = new NReco.VideoConverter.FFMpegInput(VideoFileChooser.FileName.ToString());
                ffMpeg.GetVideoThumbnail(VideoFileChooser.FileName.ToString(), PreviewImg);
                ThumbNailPicture.Image       = Image.FromStream(PreviewImg);
                EnableWatermarkChkBx.Enabled = true;
            }
        }
Beispiel #22
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";
        }
        public ActionResult Index()
        {
            string url     = "https://www.youtube.com/watch?v=7TxEZvkjwhk";
            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();

            System.IO.Stream stream = new System.IO.MemoryStream(video.GetBytes());

            // ffmpeg.ConvertMedia(videoName, null, @"C:\Downloads\result.gif", null, new ConvertSettings() { VideoFrameRate = 1, MaxDuration = 10 });
            ffmpeg.ConvertLiveMedia(stream, "mp4", @"C:\Downloads\result.gif", null, new ConvertSettings()
            {
                VideoFrameRate = 1, MaxDuration = 10
            });
            return(View());
        }
Beispiel #24
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);
        }
Beispiel #25
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);
            }
        }
Beispiel #26
0
        /// <summary>
        /// Converts the video in mp4 format with normalized settings.
        /// </summary>
        public void convertVideo(int width, int height, int frameRate)
        {
            var setting = new NReco.VideoConverter.ConvertSettings();

            setting.SetVideoFrameSize(width, height);
            setting.VideoFrameRate = frameRate;
            setting.VideoCodec     = "h264";
            setting.AudioCodec     = "ac3";

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

            ffMpegConverter.ConvertMedia(filePath,
                                         null, // autodetect by input file extension
                                         filePath + ".mp4",
                                         null, // autodetect by output file extension
                                         setting
                                         );

            this.filePath  = this.filePath + ".mp4";
            this.converted = true;
        }
Beispiel #27
0
        void SetImageSource(FileInfo fileInfo, Image source, int timeCode = 0)
        {
            MemoryStream imageStream = new MemoryStream();

            source.Resources["path"] = fileInfo.FullName;
            // image
            if (timeCode == 0)
            {
                try
                {
                    BitmapImage LoadImage = new BitmapImage();
                    LoadImage.BeginInit();
                    LoadImage.UriSource = new Uri(fileInfo.FullName);
                    LoadImage.EndInit();
                    LoadImage.Freeze();
                    source.Source = LoadImage;
                }
                catch (Exception e)
                {
                    Console.Write(e.Data);
                }
            }
            // video
            else
            {
                NReco.VideoConverter.FFMpegConverter ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                ffMpeg.GetVideoThumbnail(fileInfo.FullName, imageStream, timeCode);
                imageStream.Seek(0, SeekOrigin.Begin);
                using (var stream = imageStream)
                {
                    var bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.StreamSource = stream;
                    bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                    bitmap.EndInit();
                    bitmap.Freeze();
                    source.Source = bitmap;
                }
            }
        }
Beispiel #28
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 void getIconImage(MediaSingleElement tmpmedia, string extension)
 {
     if (!tmpmedia.Extension.Equals(".mp3"))
     {
         var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
         using (MemoryStream sampleStream = new MemoryStream())
         {
             ffMpeg.GetVideoThumbnail(new Uri(tmpmedia.mediaUri).LocalPath, sampleStream, 2);
             sampleStream.Seek(0, SeekOrigin.Begin);
             var bitmapImage = new BitmapImage();
             bitmapImage.BeginInit();
             bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
             bitmapImage.StreamSource = sampleStream;
             bitmapImage.EndInit();
             tmpmedia.IconImage = bitmapImage;
         }
     }
     else
     {
         tmpmedia.IconImage = new BitmapImage(new Uri("pack://application:,,,/XMediaPlayer;component/Icons/mp3.png"));
     }
 }
Beispiel #30
0
 private void lbVideos_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         string videofile = @"C:\\Users\\BePulverized\\Videos\\Recordings\\" + lbVideos.SelectedItem.ToString();
         var    ffmpeg    = new NReco.VideoConverter.FFMpegConverter();
         string thumbnail = @"C:\\Users\\BePulverized\\Videos\\Recordings\\" + lbVideos.SelectedItem.ToString() +
                            ".jpg";
         ffmpeg.GetVideoThumbnail(videofile, thumbnail, 20);
         pbThumbnail.ImageLocation = @"C:\\Users\\BePulverized\\Videos\\Recordings\\" +
                                     lbVideos.SelectedItem.ToString() + ".jpg";
         string date  = videofile.Substring(videofile.IndexOf('_') + 1);
         int    index = date.IndexOf(".");
         if (index > 0)
         {
             date = date.Substring(0, index);
         }
         lbRecorded.Text = "Recorded: " + date;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
        public void AgregarMarcaAguaVideo()
        {                  
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
            var variable = "C:\\marcaAgua.jpg";

            ffMpeg.Invoke("-i " + Config.VideoUrl + "\\" + SelectedGrabacion.Nombre + "_" + DateTime.Now.ToString("yyyy_dd_MM") + ".avi " + "-i " + variable + " -filter_complex \"overlay=400:330\" -codec:a copy " + Config.VideoUrl + "\\" + SelectedGrabacion.Nombre + "_" + DateTime.Now.ToString("yyyy_dd_MM") + "c.avi");
            System.IO.File.Delete(Config.VideoUrl + "\\" + SelectedGrabacion.Nombre + "_" + DateTime.Now.ToString("yyyy_dd_MM") + ".avi ");


            var pathVideoSource = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            pathVideoSource += "\\" + Config.NombreVideo + ".avi";

            dt.Stop();
            //dt.Dispatcher.InvokeShutdown();


            CurrentWindow.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(
            delegate()
            {

                TextTimer = "";
                TextBtnGrabar = "Grabar";
                ColorBtnGrabar = new SolidColorBrush(Colors.Blue);
                this.InitializeVm();
                CurrentWindow.Hide();
                ConfigDatosPersona config = new ConfigDatosPersona(this.CurrentWindow,SelectedVideo, SelectedAudio, SelectedGrabacion);
                config.ShowDialog();

            }));
                       
            

        }
        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();
                        }
                    }
                }
            }
        }
        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>();
        }