コード例 #1
2
ファイル: Treatment.cs プロジェクト: Spesiel/Library
        private static Item GenerateCacheObjectThumbnail(Color background, String pathToFile)
        {
            Item ans = new Item();
            int targetWidth = 128, targetHeight = 128;

            Image temp = null;

            /// Generate the thumbnail depending on the type of file
            if (pathToFile != null)
            {
                string fileGotten = AtRuntime.Settings.GetFile(pathToFile);

                if (Constants.AllowedExtensionsImages.Any(fileGotten.ToUpperInvariant().EndsWith))
                {
                    using (FileStream fs = new FileStream(fileGotten, FileMode.Open, FileAccess.Read))
                    {
                        using (Image image = Image.FromStream(fs, true, false))
                        {
                            //temp = GenerateThumbnailPhoto(pathToFile);
                            temp = ScaleImage(image, 128, 128);
                            GetExifFromImage(pathToFile, image).ContinueWith(t => Console.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
                        }
                    }
                }
                else
                {
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        FFMpegConverter ffmpeg = new FFMpegConverter();
                        ffmpeg.GetVideoThumbnail(pathToFile, memStream);
                        using (Image image = Image.FromStream(memStream, true, false))
                        {
                            temp = ScaleImage(image, 128, 128);
                        }
                    }
                }
            }

            Image target = new Bitmap(1, 1);
            (target as Bitmap).SetPixel(0, 0, background);
            target = new Bitmap(target, targetWidth, targetHeight);

            using (Graphics g = Graphics.FromImage(target))
            {
                g.Clear(background);
                int x = (targetWidth - temp.Width) / 2;
                int y = (targetHeight - temp.Height) / 2;
                g.DrawImage(temp, x, y);
            }

            ans.Thumbnail = target;

            return ans;
        }
コード例 #2
2
ファイル: Conversion.cs プロジェクト: Rotvig/AirPlayer
        public static string RemuxVideoToMp4(string filePath, bool convertAudioToAcc = false,
            bool convertAudioFast = false)
        {
            if (filePath.EndsWith(".mp4"))
                return null;

            var filename = Path.ChangeExtension(filePath, ".mp4");
            var arguments = "-i " + '"' + filePath + '"' + " -codec copy ";
            if (convertAudioToAcc)
                arguments = arguments + "-c:a aac ";

            arguments = arguments + '"' + filename + '"';
            var ffMpeg = new FFMpegConverter();
            ffMpeg.Invoke(arguments);
            return filename;
        }
コード例 #3
1
ファイル: AudioDownloader.cs プロジェクト: cyberus1/RainDrop
        private void ExtractAudio(string path)
        {
            FFMpegConverter converter = new FFMpegConverter();
            converter.ConvertProgress += (sender, args) =>
            {
                if (this.AudioExtractionProgressChanged != null)
                {

                    double progressPercent = args.Processed.TotalSeconds / args.TotalDuration.TotalSeconds * 100;
                    this.AudioExtractionProgressChanged(this, new ProgressEventArgs(progressPercent));
                }
            };
            //string filename = System.IO.Path.GetFileName(path); //testing
            //string dir = System.IO.Path.GetDirectoryName(this.SavePath); //testing
            //System.IO.File.Copy(path, System.IO.Path.Combine(dir, filename)); //testing
            string inputType;
            switch(Video.VideoType)
            {
                case VideoType.Mp4:
                    inputType = "mp4";
                    break;
                case VideoType.Flash:
                    inputType = "flv";
                    break;
                case VideoType.WebM:
                    inputType = "webm";
                    break;
                case VideoType.Mobile:
                    inputType = "3gp";
                    break;
                default:
                    throw new Exception("AudioDownloader.cs: VideoType unsupported");

            }
            NReco.VideoConverter.ConvertSettings cs = new ConvertSettings();
            switch(Video.AudioType)
            {
                case AudioType.Aac:
                    cs.CustomOutputArgs = "-vn -acodec copy ";
                    converter.ConvertMedia(path, inputType, this.SavePath, "mp4", cs);
                    break;
                case AudioType.Mp3:
                    cs.CustomOutputArgs = "-vn -acodec copy ";
                    converter.ConvertMedia(path, inputType, this.SavePath, "mp3", cs);
                    break;
                case AudioType.Vorbis:
                    converter.ConvertMedia(path, inputType, this.SavePath, "mp3", cs);
                    break;
                case AudioType.Unknown:
                    throw new Exception("AudioDownloader.cs: AudioType Unknown");
            }

            //converter.ConvertMedia(path, this.SavePath, "mp3");
        }
コード例 #4
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, /*$"DownloadedSongs/{video.Title}.mp3"*/ @"DownloadedSongs");

            try
            {
                await client.DownloadMediaStreamAsync(audioStreamInfo, $"DownloadedSongs/{video.Title}.webm");

                FFMpegConverter converter = new FFMpegConverter();
                converter.ConvertMedia($"DownloadedSongs/{video.Title}.webm", $"DownloadedSongs/{video.Title}.mp3", "mp3");

                TryExtractArtistAndTitle(video.Title, out var artist, out var title);

                var taggedFile = TagLib.File.Create($"DownloadedSongs/{video.Title}.mp3");
                Debug.WriteLine("DURATION : " + taggedFile.Properties.Duration);
                taggedFile.Tag.Performers = new[] { artist };
                taggedFile.Tag.Title      = title;
                taggedFile.Tag.Album      = "Downloaded from Youtube";
                taggedFile.Tag.Pictures   = picture != null ? new[] { picture } : Array.Empty <IPicture>();
                taggedFile.Save();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            this.DialogResult = true;
        }
コード例 #5
0
ファイル: VideoManager.cs プロジェクト: ImanRezaeipour/clinic
        /// <summary>
        /// برش ویدیو براساس زمان ابتدا و انتها
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task CutDownAsync(string sourceFile, int?startTime, int?endTime)
        {
            if (startTime == null)
            {
                startTime = 0;
            }
            if (endTime == null)
            {
                endTime = new FFProbe().GetMediaInfo(sourceFile).Streams.Length;
            }
            if (startTime >= endTime)
            {
                return;
            }

            var destinationFile = Path.GetFileNameWithoutExtension(sourceFile) + "_cut" + Path.GetExtension(sourceFile);
            var ffMpegConverter = new FFMpegConverter();
            var convertSettings = new ConvertSettings
            {
                Seek        = startTime,
                MaxDuration = endTime - startTime,
                VideoCodec  = "copy",
                AudioCodec  = "copy"
            };

            ffMpegConverter.ConvertMedia(sourceFile, null, destinationFile, null, convertSettings);
        }
コード例 #6
0
ファイル: VideoManager.cs プロジェクト: ImanRezaeipour/clinic
        /// <summary>
        /// ایجاد تصویر بندانگشتی از ویدیو
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task GenerateThumbnailAsync(string filePath)
        {
            var ffMpegConverter = new FFMpegConverter();
            var outputFile      = Path.Combine(HttpContext.Current.Server.MapPath(FileConst.VideosWebPath), Path.GetFileNameWithoutExtension(filePath) + "_thumb.jpg");

            ffMpegConverter.GetVideoThumbnail(filePath, outputFile);
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: NikkeArp/MediaConverter
        /// <summary>
        /// Converts slice of files to desired file format.
        /// If logging is on, prints every file to console.
        /// </summary>
        private static void ProcessSlice(ArraySlice slice, string[] files)
        {
            FFMpegConverter ffMpeg = new FFMpegConverter();

            for (int i = slice.Start; i <= slice.End; i++)
            {
                if (string.IsNullOrEmpty(files[i]))
                {
                    break;
                }
                else
                {
                    string newFile = files[i].Substring(0, files[i].Length - _args.StartFormat.Length) + _args.TargetFormat;
                    ffMpeg.ConvertMedia(files[i], newFile, _args.TargetFormat);
                    if (_args.LogEachFile)
                    {
                        lock (_lockObj) // needed for multithreading, colors get otherwise mixed up
                        {
                            string filename = files[i].Substring(files[i].LastIndexOf('\\') + 1);
                            _output.LogFileConversion(filename);
                        }
                    }
                }
            }
        }
コード例 #8
0
        public static bool ConvertVideoToMp3(string videoFilePath, string mp3FilePath, string failurePath)
        {
            try
            {
                FFMpegConverter converter = new FFMpegConverter();

                converter.ConvertMedia(videoFilePath, mp3FilePath, "mp3");

                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);

                try
                {
                    File.Create(failurePath).Close();
                }
                catch
                {
                    //ignore
                }

                return(false);
            }
        }
コード例 #9
0
 /// <summary>
 /// Returns thumbnail for episode. Also takes care of caching.
 /// </summary>
 /// <param name="id">TVDb id of Series</param>
 /// <param name="epId">TVDb id of Episode</param>
 /// <returns>BitmapImage with thumbnail or null in case of errors</returns>
 public static async Task <BitmapImage> GetEpisodeThumbnail(int id, int epId)
 {
     return(await Task.Run(async() => {
         Episode ep = GetEpisode(id, epId, true);
         if (!String.IsNullOrEmpty(ep.thumbnail) && File.Exists(ep.thumbnail))
         {
             return await LoadImage(ep.thumbnail);
         }
         else if (!String.IsNullOrEmpty(ep.filename))
         {
             string file = db + id + "\\Thumbnails\\" + Path.GetFileName(ep.filename);
             WebClient wc = new WebClient();
             Directory.CreateDirectory(Path.GetDirectoryName(file));
             wc.DownloadFile("https://www.thetvdb.com/banners/" + ep.filename, file);
             ep.thumbnail = file;
             EditEpisode(id, epId, ep);
             return await LoadImage(ep.thumbnail);
         }
         else if (ep.files.Where(x => x.Type == Episode.ScannedFile.FileType.Video).Count() > 0)
         {
             string file = ep.files.Where(x => x.Type == Episode.ScannedFile.FileType.Video).ToList()[0].NewName;
             var ffmpeg = new FFMpegConverter();
             ffmpeg.FFMpegToolPath = Environment.GetFolderPath(SpecialFolder.ApplicationData);
             string path = db + id + "\\Thumbnails\\" + ep.id + ".jpg";
             try {
                 ffmpeg.GetVideoThumbnail(file, path, 10);
                 ep.thumbnail = path;
                 EditEpisode(id, epId, ep);
                 return await LoadImage(ep.thumbnail);
             } catch (FFMpegException) {
             }
         }
         return null;
     }));
 }
コード例 #10
0
ファイル: Music.cs プロジェクト: GreatArcStudios/Equator
 private static async Task ConvertTask(FFMpegConverter ffMpegConverter, string inputFilePath, string saveName)
 {
     ffMpegConverter.Convertmedia(inputFilePath, Path.Combine(FilePaths.SaveLocation(),
                                                              FilePaths.RemoveIllegalPathCharacters(saveName)), Format.mp4);
     ffMpegConverter.Stop();
     isConverting = false;
 }
コード例 #11
0
        private VideoFileInfoSample GetVideo(Episode.ScannedFile file)
        {
            FFMpegConverter ffmpeg = new FFMpegConverter();
            FFProbe         probe  = new FFProbe();

            ffmpeg.FFMpegToolPath = probe.ToolPath = Environment.GetFolderPath(SpecialFolder.ApplicationData);
            var    info     = probe.GetMediaInfo(file.NewName);
            var    videotag = info.Streams.Where(x => x.CodecType == "video").FirstOrDefault();
            var    audiotag = info.Streams.Where(x => x.CodecType == "audio").FirstOrDefault();
            Stream str      = new MemoryStream();

            ffmpeg.GetVideoThumbnail(file.NewName, str, 10);
            Bitmap bmp = new Bitmap(str);

            return(Dispatcher.Invoke(() => {
                VideoFileInfoSample sample = sample = new VideoFileInfoSample();
                sample.ScannedFile = file;
                sample.Preview.Source = bmp.ToBitmapImage();
                sample.TopText.Text = videotag.Width + "x" + videotag.Height;
                sample.Codec.Text = videotag.CodecName;
                var lang = videotag.Tags.Where(x => x.Key == "language" || x.Key == "Language" || x.Key == "lang" || x.Key == "Lang").FirstOrDefault();
                sample.Language.Text = !String.IsNullOrEmpty(lang.Value) ? lang.Value : "-";
                sample.Fps.Text = videotag.FrameRate.ToString("##.##") + "FPS";
                sample.Pixel.Text = videotag.PixelFormat;
                sample.Created.Text = File.GetCreationTime(file.NewName).ToString("HH:mm:ss, dd. MM. yyyy");
                sample.AudioCodec.Text = audiotag.CodecName;
                return sample;
            }));
        }
コード例 #12
0
        //public static byte[] ConvertVideo(Bitmap[] frames, int frameRate, string videoFormat = Format.h264)
        //{
        //    if (frames.Length == 0) throw new ArgumentOutOfRangeException("生成视频文件的图片数不能为0");
        //    var first = frames[0];
        //    ValidatePixelFormat(first.PixelFormat);

        //    var width = first.Width;
        //    var height = first.Height;

        //    var ff = new FFMpegConverter();
        //    using (var output = new MemoryStream())
        //    {
        //        var task = ff.ConvertLiveMedia(
        //                    "rawvideo",
        //                    output,
        //                    videoFormat,
        //                    new ConvertSettings()
        //                    {
        //                        // bgr24 = windows bitmap pixel format
        //                        // framerate = set frame rate of _input_ (in this example 5 = 5 bitmaps for 1 second of the video)
        //                        CustomInputArgs = string.Format(" -pix_fmt bgr24 -video_size {0}x{1} -framerate {2} ",
        //                            width, height, frameRate)
        //                    });

        //        task.Start();

        //        foreach (var frame in frames)
        //        {
        //            task.Write(frame);
        //        }

        //        // wait until convert is finished and stop live streaming
        //        task.Stop();

        //        //var data = output.ToArray();
        //        //using (var h264stream = new FileStream("out.h264", FileMode.Create, FileAccess.Write))
        //        //{
        //        //    h264stream.Write(data, 0, data.Length);
        //        //    ff.ConvertMedia("out.h264", "h264", "out.avi", null, new ConvertSettings());
        //        //}
        //        //return data;

        //        return output.ToArray();
        //    }
        //}

        public static Bitmap[] ConvertVideo(byte[] data, int frameRate, int outputWidth, int outputHeight)
        {
            Bitmap[] frames = null;
            using (MemoryStream input = new MemoryStream(data))
            {
                var ff = new FFMpegConverter();
                using (var output = new BitmapStream(outputWidth, outputHeight))
                {
                    var task = ff.ConvertLiveMedia(
                        input, // 从内存流中读取
                        null,  // 自动从流中检测格式
                        output,
                        "rawvideo",
                        new ConvertSettings()
                    {
                        VideoFrameSize   = String.Format("{0}x{1}", outputWidth, outputHeight), // 可以设置输出图像的大小
                        CustomOutputArgs = " -pix_fmt bgr24 ",                                  // windows bitmap pixel format
                        VideoFrameRate   = frameRate
                    });


                    task.Start();
                    task.Wait(); // use task.wait if input is provided with ff.Write method
                    frames = output.GetBitmaps();
                }
            }
            return(frames);
        }
コード例 #13
0
        // encode using ffmpeg
        internal void Encode(string v)
        {
            FFMpegConverter c   = new FFMpegConverter();
            Random          rnd = new Random();

            c.Invoke(string.Format("-f concat -safe 0 -i " + v + ".txt -c copy " + v + rnd.Next(100) + ".mp4"));
        }
コード例 #14
0
 private void ConvertVideoToMp3(string title, string path)
 {
     try
     {
         int    splitCounter          = title.Split('.').Length;
         int    count                 = 0;
         string titleWithoutExtension = "";
         foreach (var item in title.Split('.'))
         {
             if (splitCounter - count != 1)
             {
                 titleWithoutExtension += item + ".";
             }
             count++;
         }
         titleWithoutExtension += "mp3";
         var    conversion = new FFMpegConverter();
         string output     = path + "\\" + title.Split('.');
         conversion.ConvertMedia((path + "\\" + title).Trim(), path + "\\" + titleWithoutExtension, "mp3");
     }
     catch (Exception ex)
     {
         MessageBox.Show("Exception details\n " + ex.ToString(), "There was an exception");
     }
 }
コード例 #15
0
        private async Task DownloadToFile(MetadataTask task, string pathToSave)
        {
            YouTubeVideo vid             = task.SelectedVideo.YoutubeVideo;
            long         totalDownloaded = 0;
            string       tempFile        = $"{pathToSave}.tmp";
            string       mp3File         = $"{pathToSave}.mp3";

            try
            {
                task.Status  = MetadataState.RUNNING;
                task.Message = String.Format(Properties.Resources.COMMAND_MSG_URI_SEARCH);
                using (ChunkDownloader client = new ChunkDownloader())
                {
                    client.OnProgress += (new ProgressHandler(task)).HandleProgress;

                    totalDownloaded = await client.DownloadToFile(vid.Uri, tempFile);
                }
                task.Message = String.Format(Properties.Resources.COMMAND_MSG_START_MP3, tempFile);

                FFMpegConverter converter = new FFMpegConverter();
                converter.ConvertProgress += (new ConvertProgressHandler(task)).HandleProgress;
                converter.ConvertMedia(tempFile, mp3File, "mp3");
                System.IO.File.Delete(tempFile);

                task.Status  = MetadataState.METADATA;
                task.Message = String.Format(Properties.Resources.COMMAND_MSG_END_MP3, mp3File);
            }
            catch (Exception ex)
            {
                task.Status  = MetadataState.ERROR;
                task.Message = ex.Message + Environment.NewLine + ex.StackTrace;
            }
        }
コード例 #16
0
        // Create thumbnail - the detail is unimportant but notice formal parameter types.
        public static void CropVideo(Stream input, Stream output)
        {
            BinaryWriter Writer = null;

            try
            {
                // Create a new stream to write to the file
                Writer = new BinaryWriter(File.Open("temp.mp4", FileMode.Create));
                BinaryReader Reader     = new BinaryReader(input);
                byte[]       imageBytes = null;
                imageBytes = Reader.ReadBytes((int)input.Length);
                // Writer raw data
                Writer.Write(imageBytes);
                Writer.Flush();
                Writer.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("*** FileWrite exception: " + e.Message);
            }

            var vid_duration = new ConvertSettings();

            vid_duration.MaxDuration = 5;

            var ffMpeg = new FFMpegConverter();

            ffMpeg.ConvertMedia("temp.mp4", "mp4", output, "mp4", vid_duration);
        }
コード例 #17
0
        public static Stream GetAudioFromVideoUrl(string filePath)
        {
            var audioStream = new MemoryStream();
            var duration    = 0;

            try
            {
                var ffmpeg = new FFMpegConverter();

                ffmpeg.ConvertProgress += (o, args) =>
                {
                    duration = Convert.ToInt32(args.Processed.TotalSeconds);
                };

                ffmpeg.ConvertMedia(filePath, null, audioStream, "wav",
                                    new ConvertSettings
                {
                    CustomOutputArgs = "-acodec pcm_s16le -ac 1 -ar 16000"
                });
            }
            catch (FFMpegException convertionException)
            {
                System.Console.WriteLine(convertionException.Message);
            }
            audioStream.Seek(0, SeekOrigin.Begin);
            return(audioStream);
        }
コード例 #18
0
        public ActionResult upload(Model_demo obj)
        {
            HttpPostedFileBase file = Request.Files["file1"];
            demo tb       = new demo();
            var  filename = Path.GetFileName(file.FileName);

            if (file.FileName != null)
            {
                string keyName    = filename;
                int    fileExtPos = keyName.LastIndexOf(".");
                if (fileExtPos >= 0)
                {
                    keyName = keyName.Substring(0, fileExtPos);
                }
                var path = Path.Combine(Server.MapPath("~/fileupload"), filename);
                file.SaveAs(path);
                string          thumbnailJPEGpath = Server.MapPath("~/fileupload/" + keyName + ".jpg");
                FFMpegConverter ffmpeg            = new FFMpegConverter();
                ffmpeg.GetVideoThumbnail(path, thumbnailJPEGpath, 2);
                var     path2 = Path.Combine(Server.MapPath("~/fileupload"), keyName + ".jpg");
                S3Class s3obj = new S3Class();
                string  str2  = s3obj.putObject("all.input.video.streaming", path, file.FileName.Replace(' ', '_'));
                string  str   = s3obj.putObject("transcoder.thumbnail.video.streaming", path2, keyName + ".jpg");
                tb.name = str;
            }


            db.demos.InsertOnSubmit(tb);
            db.SubmitChanges();
            return(View());
        }
コード例 #19
0
        public ActionResult Index()
        {
            //Download Video From Youtube
            string url     = "https://www.youtube.com/watch?v=bDuzU4XLEEs";
            var    youTube = YouTube.Default;
            var    video   = youTube.GetVideo(url);
            //------------
            //Save Video
            //System.IO.File.WriteAllBytes(@"C:\Downloads\" + video.FullName, video.GetBytes());



            var ffmpeg = new FFMpegConverter();

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

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

            //var videoName = @"C:\Downloads\" + video.FullName;
            //ffmpeg.ConvertMedia(videoName, null, @"C:\Downloads\result.gif", null, new ConvertSettings() { VideoFrameRate = 1, MaxDuration = 10 });

            return(View());
        }
コード例 #20
0
        private void DownloadOneVideoAndConvertIt(string url)
        {
            Console.WriteLine("Starting up service.");
            string title = GetVideoTitle(url); // Getting info from video

            // initiating download
            var wantedVideoFile = $"{title}.webm";
            var folder          = _folder.Replace("\\", "/");
            var arguments       = string.Format($"--continue --no-playlist --no-overwrites --restrict-filenames --extract-audio --audio-format mp3 {url} -o \"{folder}/{wantedVideoFile}\""); //--ignore-errors

            YoutubeInteraction(arguments);

            // initiating convert to mp3
            var wantedAudioFile = $"{title}.mp3";

            Console.WriteLine("Starting up ffmpeg on \"below normal\" priority."); // Making sure ffmpeg doesn't suck your computer dry
            var ffMpeg = new FFMpegConverter {
                FFMpegProcessPriority = ProcessPriorityClass.BelowNormal
            };

            Console.WriteLine("ffmpeg Created and converting media.");
            ffMpeg.ConvertMedia(_folder + "\\" + wantedVideoFile,
                                _folder + "\\" + wantedAudioFile,
                                AudioFormat.Mp3.ToString());
            Console.WriteLine("Media converted.");

            // deleting vids
            Console.WriteLine("Deleting video.");
            File.Delete(_folder + "\\" + wantedVideoFile);
        }
コード例 #21
0
        private static void createSample(Stream input, Stream output, int duration)
        {
            /* Todo
             *  Limit video files to mp4s and to a max length of 20MB.
             **/

            BinaryWriter Writer = null;

            try
            {
                // Create a new stream to write to the file
                Writer = new BinaryWriter(File.Open("temp.mp4", FileMode.Create));
                BinaryReader Reader     = new BinaryReader(input);
                byte[]       imageBytes = null;
                imageBytes = Reader.ReadBytes((int)input.Length);
                // Writer raw data
                Writer.Write(imageBytes);
                Writer.Flush();
                Writer.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("*** FileWrite exception: " + e.Message);
            }

            var vid_duration = new ConvertSettings();

            vid_duration.MaxDuration = duration;

            var ffMpeg = new FFMpegConverter();

            ffMpeg.ConvertMedia("temp.mp4", "mp4", output, "mp4", vid_duration);
        }
コード例 #22
0
        private void btnGetFrames_Click(object sender, EventArgs e)
        {
            string inputPath  = tbVideo.Text;
            string outputPath = tboutdir.Text;

            try
            {
                if (inputPath != null && outputPath != null)
                {
                    float           duration  = GetVideoDuration(inputPath);
                    FFMpegConverter ffmegc    = new FFMpegConverter();
                    float           frameTime = 0.3f;
                    int             counter   = 1;
                    while (frameTime <= duration)
                    {
                        string img = Path.Combine(outputPath, string.Format("frame{0}.jpg", counter));
                        ffmegc.GetVideoThumbnail(inputPath, img, frameTime);
                        counter++;
                        frameTime += 0.3f;
                        Image pic = resizeImage(new Bitmap(img), new Size(293, 163));
                        picBox.Image = new Bitmap(pic);
                    }
                }
            }
            catch (FFMpegException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
コード例 #23
0
        static async Task <MemoryStream> getFrameFromVideo(float startTime)
        {
            Stream rawBmpOutputStream = new MemoryStream();
            var    ffProbe            = new NReco.VideoInfo.FFProbe();
            var    videoInfo          = ffProbe.GetMediaInfo(path);
            var    convertSettings    = new ConvertSettings()
            {
                VideoFrameSize = "1280*720", // lets resize to exact frame size
                VideoFrameRate = 24,         // lets consume 24 frames per second
                MaxDuration    = 1           // lets consume live stream for first 5 seconds
            };

            convertSettings.Seek = startTime;
            var videoConv  = new FFMpegConverter();
            var ffMpegTask = videoConv.ConvertLiveMedia(
                path,
                null,               // autodetect live stream format
                rawBmpOutputStream, // this is your special stream that will capture bitmaps
                Format.gif,
                convertSettings);

            ffMpegTask.Start();
            ffMpegTask.Wait();
            return((MemoryStream)rawBmpOutputStream);
        }
コード例 #24
0
 public string Start()
 {
     this.converter = new FFMpegConverter();
     this.LoadXml();
     this.CreateMovie();
     return(this.AddAudio());
 }
コード例 #25
0
        private Task ConvertStream(HttpContent httpContent, Stream outputStream)
        {
            Task convertTask = new Task(() => {

                var convertSettings = new ConvertSettings {
                    CustomOutputArgs = "-map 0",
                    CustomInputArgs = "-vcodec h264"
                };

                var ffMpeg = new FFMpegConverter();
                ffMpeg.ConvertProgress += FfMpeg_ConvertProgress;
                ffMpeg.LogReceived += FfMpeg_LogReceived;

                //var task = ffMpeg.ConvertLiveMedia(Format.h264, "C:\\Work\\Test\\converted.avi", Format.avi, convertSettings);
                var task = ffMpeg.ConvertLiveMedia(Format.h264, outputStream, Format.mpeg, convertSettings);

                task.Start();

                var ffmpegStream = new FFMPegStream(task);
                var copyTask = httpContent.CopyToAsync(ffmpegStream);
                copyTask.Wait();
                ffmpegStream.Close();

                task.Wait();

                //                ffMpeg.ConvertMedia(@"C:\Work\Test\MyHomeSecureNode\devices\test\video.h264", "C:\\Work\\Test\\converted.avi", Format.avi);

                outputStream.Close();
            });

            convertTask.Start();
            return convertTask;
        }
コード例 #26
0
        private int AttemptConversion()
        {
            int status = WORKING;

            FFMpegConverter converter = new FFMpegConverter();

            try
            {
                converter.ConvertMedia(this.orig_path, this.dest_path, TARGET_ENCODE);
                status = SUCCESS;
            }
            catch (FFMpegException e)
            {
                System.Diagnostics.Debug.WriteLine("Media Converter Failed: " + e.Message);
                status = FAILURE;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("VDXMediaConverter Error: " + e.Message);
                System.Diagnostics.Debug.WriteLine(this.orig_path + " : " + this.dest_path);
                status = FAILURE;
            }
            converter.Abort();
            return(status);
        }
コード例 #27
0
ファイル: FFmpegExtractAudio.cs プロジェクト: Mefgalm/PlayCat
        public async Task <IFile> ExtractAsync(IFile videoFile)
        {
            if (videoFile == null)
            {
                throw new ArgumentNullException(nameof(videoFile));
            }

            if (videoFile.StorageType != StorageType.FileSystem)
            {
                throw new Exception("FFMpeg can work only with file on FileSystem");
            }

            //get full path for audio
            string audioFullpath = Path.Combine(
                _fileResolver.GetAudioFolderPath(StorageType.FileSystem),
                videoFile.Filename + "." + _audioOptions.Value.DefaultFormat);

            //get video
            string videofilePath = _fileResolver.VideoFilePath(videoFile.Filename, videoFile.Extension, StorageType.FileSystem);

            if (File.Exists(audioFullpath))
            {
                File.Delete(audioFullpath);
            }

            //extract audio from video
            var ffMpeg = new FFMpegConverter();

            ffMpeg.LogReceived += FfMpeg_LogReceived;

            ffMpeg.Invoke(
                string.Format(FFMpegExtractAudioFormat,
                              videofilePath,
                              _audioOptions.Value.DefaultFormat,
                              _audioOptions.Value.BitRate,
                              audioFullpath));

            var cancellationTokenSource = new CancellationTokenSource();

            //delete video
            File.Delete(videofilePath);

            try
            {
                await Task.Delay(10000, _cancellationTokenSource.Token);
            } catch (TaskCanceledException)
            {
                //do nothing cancel it okey
            }

            //return info about audio file
            return(new PCFile()
            {
                Filename = videoFile.Filename,
                Extension = "." + _audioOptions.Value.DefaultFormat,
                Duration = _duration,
                StorageType = StorageType.FileSystem,
            });
        }
コード例 #28
0
        public RouteLapser(string courseFilePath)
        {
            CourseFilePath        = courseFilePath;
            TrainingCenterXmlData = RouteLapser.OpenCourse(CourseFilePath);

            FFMpegClient    = new FFMpegConverter();
            GoogleMapClient = new GoogleMapsApi();
        }
コード例 #29
0
 public ThumbnailResult(int width, int height, DwsFileInfo fileInfo, IHostingEnvironment env, FFMpegConverter converter)
 {
     Width     = width;
     Height    = height;
     FileInfo  = fileInfo;
     HostEnv   = env;
     Converter = converter;
 }
コード例 #30
0
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="convertInputFilePath">File path convert from</param>
 /// <param name="convertOutputFilePath">File path convert to</param>
 /// <param name="format">Format <see cref="Formats"/></param>
 public Converter(string convertInputFilePath, string convertOutputFilePath, Formats format)
 {
     _convertInputFilePath  = convertInputFilePath;
     _convertOutputFilePath = convertOutputFilePath;
     _format    = format;
     _convertor = new FFMpegConverter();
     _convertor.ConvertProgress += UpdateProgress;
 }
コード例 #31
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileRepository"></param>
        /// <param name="env"></param>
        /// <param name="settings"></param>
        /// <param name="config"></param>
        public FileOpsController(IFileRepository fileRepository, IHostingEnvironment env, IOptions <DwsSettings> settings, IConfiguration config) : base(env, settings)
        {
            FileRepository = fileRepository;
            FileRepository.BeginTransaction();

            Converter = new FFMpegConverter();
            //License.SetLicenseKey(DWSsettings.NRecoLicense.KeyName, DWSsettings.NRecoLicense.KeyValue);
        }
コード例 #32
0
ファイル: Global.asax.cs プロジェクト: pear171902790/Driver
 private void TestConvert3gpToMp4()
 {
     var voicePath = Server.MapPath("~/Voice/");
     var voiceName = "87de70cc-2bdf-4ad1-b4f7-7bedd68c5975_2016718211939";
     var ffMpeg = new FFMpegConverter();
     ffMpeg.ConvertMedia(voicePath + voiceName + ".3gp", voicePath + voiceName + ".mp4", Format.mp4);
     File.Delete(voicePath + voiceName + ".3gp");
 }
コード例 #33
0
 private void ConvertFlvToAudio(string ext, FFMpegConverter converter)
 {
     string[] flvFilePaths = Directory.GetFiles(this.dataDirectoryPath, "*.flv");
     foreach (string flvPath in flvFilePaths)
     {
         string newWavPath = Path.Combine(this.destDirectoryPath, Path.GetFileNameWithoutExtension(flvPath) + "_old." + ext);
         converter.ConvertMedia(flvPath, newWavPath, ext);
     }
 }
コード例 #34
0
        public static Movie Make(string path)
        {
            var converter = new FFMpegConverter();
            var image     = new MemoryStream();

            converter.GetVideoThumbnail(path, image);
            image.Position = 0;
            return(new Movie(path, Smaller(image)));
        }
コード例 #35
0
        private void Init()
        {
            _age       = new FaceAge(AppId, AgeKey);
            _gender    = new FaceGender(AppId, GenderKey);
            _traking   = LocatorFactory.GetTrackingLocator(AppId, FtKey, _age, _gender) as FaceTracking;
            _detection = LocatorFactory.GetDetectionLocator(AppId, FdKey) as FaceDetection;
            _recognize = new FaceRecognize(AppId, FrKey);
            _processor = new FaceProcessor(_traking, _recognize);

            //init cache
            if (Directory.Exists(FaceLibraryPath))
            {
                var files = Directory.GetFiles(FaceLibraryPath);
                foreach (var file in files)
                {
                    var info = new FileInfo(file);
                    _cache.Add(info.Name.Replace(info.Extension, ""), File.ReadAllBytes(file));
                }
            }

            stride     = width * pixelSize;
            bufferSize = stride * height;

            _pImage = Marshal.AllocHGlobal(bufferSize);
            _image  = new Bitmap(width, height, stride, PixelFormat.Format24bppRgb, _pImage);

            var ffmpeg = new FFMpegConverter();

            outputStream = new MemoryStream();

            var setting =
                new ConvertSettings
            {
                CustomOutputArgs = "-s 1920x1080", //根据业务需求-r参数可以调整,取决于摄像机的FPS
            };                                     //-s 1920x1080 -q:v 2 -b:v 64k

            //-an -r 15 -pix_fmt bgr24 -updatefirst 1
            //task = ffmpeg.ConvertLiveMedia("rtsp://*****:*****@192.168.1.64:554/h264/ch1/main/av_stream", null,
            //    outputStream, Format.raw_video, setting);

            /*
             * USB摄像头捕获
             * 通过ffmpeg可以捕获USB摄像,如下代码所示。
             * 首先通过:ffmpeg -list_devices true -f dshow -i dummy命令,可以列出系统中存在的USB摄像设备(或通过控制面板的设备管理工具查看设备名称),例如在我电脑中叫USB2.0 PC CAMERA。
             * 然后根据捕获的分辨率,修改视频图形信息,包括width和height,一般像素大小不用修改,如果要参考设备支持的分辨率,可以使用:
             * ffmpeg -list_options true -f dshow -i video="USB2.0 PC CAMERA"命令
             */
            task = ffmpeg.ConvertLiveMedia("video=Logitech HD Webcam C270", "dshow",
                                           outputStream, Format.raw_video, setting);

            task.OutputDataReceived += DataReceived;
            task.Start();

            _renderTask = new Task(Render);
            _renderTask.Start();
        }
コード例 #36
0
ファイル: Form1.cs プロジェクト: starik222/AnimeManager
 private void GetScrin()
 {
     Progress(1);
     ProgressVisibl(true);
     this.files_a_scrinTableAdapter.Fill(this.anime_ArchiveDataSet.files_a_scrin);
     DataTable dt = files_a_scrinTableAdapter.GetData();
     int count = dt.Rows.Count * 15 + 3;
     int p = 0;
     for (int j = 0; j < dt.Rows.Count; j++)
     {
         try
         {
             FFMpegConverter ffMpeg = new FFMpegConverter();
             MediaInfoLib.MediaInfo mi = new MediaInfoLib.MediaInfo();
             MediaInfoDotNet.MediaFile m = new MediaFile(dt.Rows[j]["Path_s"].ToString());
             List<Image> images = new List<Image>();
             TimeSpan ts = TimeSpan.FromMilliseconds(m.duration);
             int col = 15;
             int period = Convert.ToInt32(ts.TotalSeconds) / col;
             int w = 0, h = 0, column = 3;
             for (int i = 1; i <= col; i++)
             {
                 p++;
                 Progress((p * 100) / count);
                 MemoryStream ms = new MemoryStream();
                 Image image;
                 ffMpeg.GetVideoThumbnail(dt.Rows[j]["Path_s"].ToString(), ms, i * period);
                 if (ms.Length == 0)
                     continue;
                 image = Image.FromStream(ms);
                 w = image.Width;
                 h = image.Height;
                 //pictureBox1.Image = image;
                 images.Add(image);
             }
             Image mm = Draw(images, w, h, column);
             mm = ResizeImg(mm, 30);
             MemoryStream mem = new MemoryStream();
             mm.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp);
             files_a_scrinTableAdapter.Update(ReadBytesFromImage(mem), Convert.ToInt32(dt.Rows[j]["kod_files"]));
         }
         catch (Exception ex)
         {
             continue;
         }
     }
     Progress(100);
     ProgressVisibl(false);
 }
コード例 #37
0
ファイル: Converter.cs プロジェクト: Flasheur111/CatMyVideo
 public Converter()
 {
     converter = new FFMpegConverter();
 }
コード例 #38
0
        static void Main(string[] args)
        {
            var f = new FFMpegConverter();

            // Get thumbnail at a specified time in seconds
            Console.WriteLine("Generating image...");
            f.GetVideoThumbnail(@"C:\Users\npasumarthy\Downloads\Test.mp4", @"C:\Users\npasumarthy\Downloads\TestThumbnail.jpg", 3);

            //Extract Audio from Video
            Console.WriteLine("Extracting Audio...");
            f.ConvertMedia(@"C:\Users\npasumarthy\Downloads\Test.mp4", @"C:\Users\npasumarthy\Downloads\Test2.mp3", "mp3");

            // OCR the image
            // OcrFromUrl();
            Console.WriteLine("OCR...");
            String filename = @"C:\Users\npasumarthy\Downloads\TestThumbnail.jpg";
            //filename = @"C:\Users\npasumarthy\Downloads\Demo.jpg";
            //filename = @"C:\Users\npasumarthy\Downloads\Demo2.jpg";
            var textFromImage = OcrFromFile(filename);
            Console.WriteLine(textFromImage);

            // Clean the Text retuned from OCR
            Console.WriteLine("Cleaning the OCR result");
            var cleanedText = textFromImage.Replace(@"\n", "");

            // Save the audio file and OCR file as response to client
            Console.WriteLine("OCR to Audio...");
            String audioUrl = TextToSpeech(textFromImage);
            Console.WriteLine("\n\n" + audioUrl + "\n\n");
            Process.Start("wmplayer.exe", audioUrl);
        }
コード例 #39
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime time = DateTime.Now;
            string Body = string.Empty;
            var ffMpeg = new FFMpegConverter();
            txt_time.Text = time.ToLongTimeString();
            if(IsRecording)
            {
                if(time<time_stop)
                {
                    lblGrabar.Visible = true;
                    lblGrabar.Text = "Grabando hasta " + time_stop.ToLongTimeString();
                    //Bitmap Imagen = (Bitmap)pcb_video.Image;

                    writer.AddFrame(video);
                    //FileWriter.WriteVideoFrame(video);
                    if(time<time_stop.AddSeconds(-8))
                    {
                        //txtMensajes.Text += "Capturando la foto con imagen de movimiento" + "\r\n";
                        PhotoFileName = "C:/Users/Alex/Desktop/DEMO/photo_" + DateTime.Now.ToShortDateString().Replace("/", "-") + DateTime.Now.ToShortTimeString().Replace(":", "_") + ".png";
                        foto.Save(PhotoFileName, System.Drawing.Imaging.ImageFormat.Png);
                    }
                }
                else
                {
                    txtMensajes.Text += "Fin de la grabación...!" + "\r\n";
                    writer.Close();

                    pcb_video.Image = Properties.Resources.offline;
                    //FileWriter.Close();
                    txtMensajes.Text += "Compresión de video...!" + "\r\n";
                    ffMpeg.ConvertMedia(VideoFileName, VideoFileName.Replace(".avi",".mp4"), Format.mp4);
                    txtMensajes.Text += "Intentando subir video a servidor de almacenamiento externo...!" + "\r\n";
                    subirArchivo(VideoFileName.Replace(".avi", ".mp4"));
                    txtMensajes.Text += "Video " + this.UploadFileName.Substring(8,UploadFileName.Length-8) +" cargado a servidor de almacenamiento externo...!" + "\r\n";
                    txtMensajes.Text += "Envío de e-mail...!" + "\r\n";
                    Body = "<a href='https://dl.dropboxusercontent.com/u/72924944/" + this.UploadFileName.Substring(8, UploadFileName.Length - 8) + "'>VIDEO</a>" +
                            "<p>" +
                            "<a href='mailto:[email protected][email protected]&amp;subject=Ignorar%20Evento&amp;body=Se%20ha%20detectado%20movimiento%20en%20el%20sistema%20de%20seguridad%2C%20pero%20Ud.%20ha%20decidido%20ignorar%20este%20evento.%20El%20sistema%20detendr%C3%A1%20el%20servicio%20por%2030%20Minutos.'>IGNORAR</a>";
                    enviar_Correo("*****@*****.**", "ALERTA - Sistema de Seguridad ha detectado movimiento", Body);
                    IsRecording = false;
                    lblGrabar.Visible = false;
                    time_stop = DateTime.MinValue;
                }
            }
        }
コード例 #40
0
 public void WriteVideoThumbnailPicture(string videoFilePath, string imageFilePath, PictureSize size, float? frameTime)
 {
     var ffmpeg = new FFMpegConverter();
     ffmpeg.GetVideoThumbnail(videoFilePath, imageFilePath, frameTime);
 }
コード例 #41
0
        public IHttpActionResult UploadVideo()
        {
            var files = HttpContext.Current.Request.Files;
            if (files.Count == 0)
                return Response(new { Success = false, Message = "No file uploaded" });

            var file = files[0];
            //and it's name
            var fileName = file.FileName;

            //file extension and it's type
            var fileExtension = Path.GetExtension(fileName);
            if (!string.IsNullOrEmpty(fileExtension))
                fileExtension = fileExtension.ToLowerInvariant();

            var contentType = file.ContentType;

            if (string.IsNullOrEmpty(contentType))
            {
                contentType = VideoUtility.GetContentType(fileExtension);
            }

            if (contentType == string.Empty)
            {
                return Response(new { Success = false, Message = "Invalid file type" });
            }

            var tickString = DateTime.Now.Ticks.ToString();
            var savePath = Path.Combine(_mediaSettings.VideoSavePath, tickString + fileExtension);
            file.SaveAs(HostingEnvironment.MapPath(savePath));
            //TODO: Create a standard controller for handling uploads
            //wanna generate the thumbnails for videos...ffmpeg is our friend
            var ffmpeg = new FFMpegConverter();
            var thumbnailFilePath = Path.Combine(_mediaSettings.PictureSavePath) + tickString + ".thumb.jpg";
            ffmpeg.GetVideoThumbnail(HostingEnvironment.MapPath(savePath), HostingEnvironment.MapPath(thumbnailFilePath));
            //save the picture now

            return Json(new {
                Success = true,
                VideoUrl = savePath.Replace("~", ""),
                ThumbnailUrl = thumbnailFilePath.Replace("~", ""),
                MimeType = file.ContentType
            });
        }
コード例 #42
-1
ファイル: Conversion.cs プロジェクト: Rotvig/AirPlayer
        public static string ReencodeVideoToMp4(string filePath)
        {
            if (filePath.EndsWith(".mp4"))
                return null;

            var filename = Path.ChangeExtension(filePath, ".mp4");

            var ffMpeg = new FFMpegConverter();
            ffMpeg.ConvertProgress += ConvertProgressEvent;
            ffMpeg.ConvertMedia(filePath, filename, Format.mp4);

            return filename;
        }
コード例 #43
-1
        public static async Task NRecoConvertToWavAsync(string srcFilepath, string dstFolder, int dstBitrate, double dstVolume, string dstFilename = null)
        {
            if(string.IsNullOrEmpty(dstFilename))
                dstFilename = Path.GetFileNameWithoutExtension(srcFilepath);
            
            dstFilename = RemoveInvalidFilenameCharacters(dstFilename);
            string destination = $"{dstFolder}\\{dstFilename}.wav";

            var converter = new FFMpegConverter();

            await Task.Run(() => converter.ConvertMedia(srcFilepath, "mp4", destination, "wav", new ConvertSettings()
            {
                AudioCodec = "pcm_s16le",
                AudioSampleRate = dstBitrate,
                CustomOutputArgs = "-map_metadata -1 -aq 100 -ac 1"
            }));

            await FixFFmpegWavFileHeader(destination);
        }
コード例 #44
-1
        /// <summary>
        /// Run Convert Worker
        /// </summary>
        /// <param name="inputPath">Input file path</param>
        /// <param name="outputPath">Output file path</param>
        /// <param name="format">Video file format</param>
        /// <param name="arguments">Arguments for ffmpeg</param>
        /// <param name="passNumber">Pass number</param>
        private void RunConvertWorker(string inputPath, string outputPath, string format, string[] arguments, int passNumber)
        {
            int passCount = arguments.Length;
            if (passNumber > passCount - 1) return;

            string currentPassArguments = arguments[passNumber];
            string currentOutputPath = outputPath;
            string toolTipText = "Выполняется конвертирование";

            if (passCount > 1)
            {
                toolTipText = string.Format("Выполняется проход {0} из {1}", (passNumber + 1), passCount);
                if (passNumber < (passCount - 1))
                    currentOutputPath = "NUL";
            }

            bw = new BackgroundWorker();
            bw.WorkerSupportsCancellation = true;
            bw.WorkerReportsProgress = true;
            bw.ProgressChanged += new ProgressChangedEventHandler(delegate (object sender, ProgressChangedEventArgs e)
            {
                int progressPercentage = Math.Min(100, e.ProgressPercentage);
                if (progressPercentage > 0)
                {
                    ProgressBarPercentage(progressPercentage);
                }
                showToolTip(toolTipText);
            });
            bw.DoWork += delegate (object sender, DoWorkEventArgs e)
            {
                try
                {
                    FFMpegConverter ffMpeg = new FFMpegConverter();
                    ffMpeg.FFMpegProcessPriority = ProcessPriorityClass.Idle;
                    ffMpeg.FFMpegToolPath = Path.Combine(Environment.CurrentDirectory, "Binaries");

                    ConvertSettings settings = new ConvertSettings();
                    settings.CustomOutputArgs = currentPassArguments;

                    ffMpeg.ConvertProgress += delegate (object sendertwo, ConvertProgressEventArgs etwo)
                    {
                        int perc = (int)((etwo.Processed.TotalMilliseconds / etwo.TotalDuration.TotalMilliseconds) * 100);
                        bw.ReportProgress(perc);
                        if (bw.CancellationPending)
                            ffMpeg.Stop();
                    };

                    ffMpeg.ConvertMedia(inputPath, null, currentOutputPath, format, settings);
                }
                catch (Exception ex)
                {
                    if (!ex.Message.StartsWith("Exiting normally") && !closeApp)
                        MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                    return;
                }
            };
            bw.RunWorkerCompleted += delegate (object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Cancelled)
                {
                    converting = false;

                    // reset pbar
                    ResetProgressBar();
                    toolStripProgressBar.Visible = false;

                    buttonGo.Text = buttonGoText;
                    buttonGo.Enabled = true;

                    showToolTip("Конвертирование отменено");

                    if (closeApp)
                        Application.Exit();

                    return;
                }

                // run next pass
                if (passCount > 1 && passNumber < (passCount - 1))
                {
                    RunConvertWorker(inputPath, outputPath, format, arguments, passNumber + 1);
                }
                else
                {
                    converting = false;

                    // 100% done!
                    ProgressBarPercentage(100);

                    buttonGo.Text = buttonGoText;
                    buttonGo.Enabled = true;

                    showToolTip("Готово");
                    if (MessageBox.Show("Открыть полученный файл?", "Конвертирование выполнено", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            Process.Start(outputPath);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            };

            ResetProgressBar();
            toolStripProgressBar.Visible = true;

            buttonGo.Text = "Отменить";
            buttonGo.Enabled = true;

            converting = true;
            showToolTip(toolTipText);
            bw.RunWorkerAsync();
        }
コード例 #45
-1
        private void ExtractAudio(string path)
        {
            FFMpegConverter converter = new FFMpegConverter();

            converter.ConvertProgress += (sender, args) =>
            {
                if (this.AudioExtractionProgressChanged != null)
                {
                    double progressPercent = args.Processed.TotalSeconds / args.TotalDuration.TotalSeconds * 100;
                    this.AudioExtractionProgressChanged(this, new ProgressEventArgs(progressPercent));
                }
            };

            converter.ConvertMedia(path, this.SavePath, "mp3");
        }
コード例 #46
-1
        public ActionResult UploadPosition([ModelBinder(typeof(JsonBinder<UploadPositionRequest>))]UploadPositionRequest uploadPositionRequest)
        {
            try
            {
                var token = Request.Headers["Token"];
                if (!CheckToken(token)) return ApiResponse.NotSignIn;
                var guid = new Guid(token);
                using (var context = new DriverDBContext())
                {
                    var user = context.Users.SingleOrDefault(x => x.Id == guid);
                    if (user == null)
                    {
                        return ApiResponse.UserNotExist;
                    }
                    var postion = new Position() { Id = Guid.NewGuid() };
                    postion.UploadBy = user.Id;
                    postion.Address = HttpUtility.UrlDecode(uploadPositionRequest.Address, Encoding.UTF8);
                    postion.Latitude = uploadPositionRequest.Latitude;
                    postion.Longitude = uploadPositionRequest.Longitude;
                    postion.UploadTime = DateTime.Now;

                    if (!string.IsNullOrEmpty(uploadPositionRequest.Voice))
                    {
                        Task.Run(() =>
                        {
                            try
                            {
                                var bytes = Convert.FromBase64String(uploadPositionRequest.Voice);
                                var voiceName = user.Id + "_" + CurrentTime;
                                var voicePath = Server.MapPath("~/Voice/");
                                var sourceFileFullName = voicePath + voiceName + ".3gp";
                                var finalFileFullName = voicePath + voiceName + ".mp4";
                                if (!Directory.Exists(voicePath))
                                {
                                    Directory.CreateDirectory(voicePath);
                                }
                                using (var fs = new FileStream(sourceFileFullName, FileMode.Create))
                                {
                                    fs.Write(bytes, 0, bytes.Length);
                                    fs.Close();
                                }
                                var ffMpeg = new FFMpegConverter();
                                ffMpeg.ConvertMedia(sourceFileFullName, finalFileFullName, Format.mp4);
                                System.IO.File.Delete(sourceFileFullName);
                                postion.Voice = finalFileFullName;
                            }
                            catch (Exception ex)
                            {
                                var logger = LogManager.GetLogger(typeof (HttpRequest));
                                logger.Error(
                                    "------------------------api/Voice error-------------------------------\r\n" +
                                    ex.Message);
                            }
                        });
                    }

                    context.Positions.Add(postion);
                    context.SaveChanges();
                    return ApiResponse.OK();
                }
            }
            catch (Exception ex)
            {
                var logger = LogManager.GetLogger(typeof(HttpRequest));
                logger.Error("------------------------api/UploadPosition error-------------------------------\r\n" + ex.Message);
                return ApiResponse.UnknownError;
            }
        }
コード例 #47
-1
ファイル: frmMain.cs プロジェクト: xKaizo/YoutubeToMp3
        private void btnDownloadSelected_Click(object sender, EventArgs ea)
        {
            foreach (YoutubeListView.AudioItem selectedItem in _LstYoutubes.SelectedItems())
            {
                if (selectedItem.DownloadStatus != YoutubeListView.AudioItem.DownloadStatuses.NotDownloaded) continue;

                var invalidChars = Path.GetInvalidFileNameChars();
                string fixedTitle = new string(selectedItem._Audio.Title.Where(x => !invalidChars.Contains(x)).ToArray());

                YoutubeDownloader youtubeDownloader = new YoutubeDownloader();
                youtubeDownloader.OnDownloadProgressChanged += (s, e) =>
                {
                    selectedItem.DownloadStatus = YoutubeListView.AudioItem.DownloadStatuses.Downloading;
                    selectedItem.DownloadProgress = e.ProgressPercentage * 0.5f;
                };
                youtubeDownloader.OnDownloadFailed += (s, ex) =>
                {
                    selectedItem.DownloadStatus = YoutubeListView.AudioItem.DownloadStatuses.Error;
                    MessageBox.Show(String.Format("An error has occured.\n{0}", ex.ToString()), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                };
                youtubeDownloader.OnDownloadCompleted += (s, video) =>
                {
                    selectedItem.DownloadStatus = YoutubeListView.AudioItem.DownloadStatuses.Converting;

                    FFMpegConverter ffMpeg = new FFMpegConverter();
                    ffMpeg.ConvertProgress += (ss, progress) =>
                    {
                        selectedItem.DownloadProgress = 50 + (float)((progress.Processed.TotalMinutes / progress.TotalDuration.TotalMinutes) * 50);
                    };

                    FileStream fileStream = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + fixedTitle + ".mp3", FileMode.Create);

                    ffMpeg.LogReceived += async (ss, log) =>
                    {
                        if (!log.Data.StartsWith("video:0kB")) return;

                        Invoke(new MethodInvoker(() =>
                        {
                            selectedItem.DownloadStatus = YoutubeListView.AudioItem.DownloadStatuses.Completed;
                        }));

                        await Task.Delay(1000);
                        fileStream.Close();
                        File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + fixedTitle + ".mp4");
                    };

                    new Thread(() => ffMpeg.ConvertMedia(
                        Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + fixedTitle + ".mp4",
                        "mp4",
                        fileStream,
                        "mp3",
                        new ConvertSettings { AudioCodec = "libmp3lame", CustomOutputArgs = "-q:a 0" }
                        )).Start(); 
                };

                var highestQualityAvailable = selectedItem._Audio.GetHighestQualityTuple();
                youtubeDownloader.DownloadAudioAsync(selectedItem._Audio, highestQualityAvailable.Item1, highestQualityAvailable.Item2, Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + fixedTitle + ".mp4");
            }
        }
コード例 #48
-1
        private void button2_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                FFMpegConverter ffMpeg = new FFMpegConverter();
                MediaInfoLib.MediaInfo mi = new MediaInfoLib.MediaInfo();
                MediaInfoDotNet.MediaFile m = new MediaFile(openFileDialog1.FileName);
                List<Image> images = new List<Image>();
                TimeSpan ts = TimeSpan.FromMilliseconds(m.duration);
                int col = 15;
                int period = Convert.ToInt32(ts.TotalSeconds) / col;
                int w=0, h=0, column = 3;
                for (int i = 1; i <= col; i++)
                {
                    MemoryStream ms = new MemoryStream();
                    Image image;
                    ffMpeg.GetVideoThumbnail(openFileDialog1.FileName, ms, i * period);
                    image = Image.FromStream(ms);
                    w = image.Width;
                    h = image.Height;
                    //pictureBox1.Image = image;
                    images.Add(image);
                }
                Image mm = Draw(images, w, h, column);
                mm = ResizeImg(mm, 28);
                pictureBox1.Image = mm;

            }
        }