コード例 #1
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");
        }
コード例 #2
0
        public void ConverterVideo(string caminhoArquivo, string nomeArq)
        {
            var ffMpeg = new FFMpegConverter();

            ffMpeg.ConvertMedia(caminhoArquivo, ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.historiaMidiaDiretorio, nomeArq + "Temp.mp4"), Format.mp4);
            ffMpeg.ConvertMedia(caminhoArquivo, ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.historiaMidiaDiretorio, nomeArq + "Temp.webm"), Format.webm);
            ffMpeg.ConvertMedia(caminhoArquivo, ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.historiaMidiaDiretorio, nomeArq + "Temp.ogv"), Format.ogg);

            File.Move(ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.historiaMidiaDiretorio, nomeArq + "Temp.webm"), ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.historiaMidiaDiretorio, nomeArq + ".webm"));
            File.Move(ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.historiaMidiaDiretorio, nomeArq + "Temp.ogv"), ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.historiaMidiaDiretorio, nomeArq + ".ogv"));
            File.Move(ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.historiaMidiaDiretorio, nomeArq + "Temp.mp4"), ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.historiaMidiaDiretorio, nomeArq + ".mp4"));
        }
コード例 #3
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);
                        }
                    }
                }
            }
        }
コード例 #4
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);
        }
コード例 #5
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);
            }
        }
コード例 #6
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);
        }
コード例 #7
0
ファイル: VideoConverter.cs プロジェクト: johnsrsly/STMp3MVVM
 public string ConvertVideoToMp3(string path)
 {
     try
     {
         var newFile = Path.ChangeExtension(path, "mp3");
         _converter.ConvertProgress += (s, e) =>
         {
             var progress = e.Processed.Ticks / (double)e.TotalDuration.Ticks * 100;
             VideoConvertEvent(s, new VideoEventArgs {
                 ConvertProgress = progress
             });
         };
         _converter.ConvertMedia(path, newFile, "mp3");
         File.Delete(path);
         return(path);
     }
     catch (Exception e)
     {
         using (var sw = new StreamWriter("ExceptionLog.txt", true))
         {
             sw.WriteLine(DateTime.Now);
             sw.WriteLine(e.ToString());
             sw.WriteLine();
             sw.Flush();
             sw.Close();
         }
         return(null);
     }
 }
コード例 #8
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;
            }
        }
コード例 #9
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);
        }
コード例 #10
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");
     }
 }
コード例 #11
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);
        }
コード例 #12
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);
        }
コード例 #13
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);
        }
コード例 #14
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;
        }
コード例 #15
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");
 }
コード例 #16
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);
     }
 }
コード例 #17
0
 /// <inheritdoc />
 public void StartConvert()
 {
     IsStarted = true;
     Task.Factory.StartNew(() =>
     {
         _convertor?.ConvertMedia(_convertInputFilePath, _convertOutputFilePath, GetFormat());
         IsStarted = false;
     });
 }
コード例 #18
0
        //FFMpegConverter conv = new FFMpegConverter();
        //ConvertSettings convSet = new ConvertSettings();

        private void ExeConv()
        {
            Debug.WriteLine(ConvertArgs);

            FFMpegConverter conv = new FFMpegConverter();

            conv.ConvertProgress += UpdateProgress;

            ConvertSettings convSet = new ConvertSettings();

            convSet.CustomOutputArgs = ConvertArgs;

            string outExtension = "";

            string outFormat = "";

            string inFormat = "";

            if (MkvOut)
            {
                outExtension = ".mkv";
                outFormat    = Format.matroska;
            }
            else if (Mp4Out)
            {
                outExtension = ".mp4";
                outFormat    = Format.mp4;
            }

            if (_filePathName.Contains("mkv"))
            {
                inFormat = Format.matroska;
            }
            else if (_filePathName.Contains("mp4"))
            {
                inFormat = Format.mp4;
            }

            string outName = OutFileName + outExtension;

            //ConsoleAllocator.ShowConsoleWindow();

            //ProgressVisible = Visibility.Visible;
            try
            {
                conv.ConvertMedia(_filePathName, inFormat, _filePathName.Remove(_filePathName.Length - FileName.Length) + outName, outFormat, convSet);
            }
            catch (FFMpegException e)
            {
                Debug.WriteLine(e.StackTrace);
            }

            StartVisible = Visibility.Visible;

            //ConsoleAllocator.HideConsoleWindow();
        }
コード例 #19
0
ファイル: Form1.cs プロジェクト: marceljdb/conversorTest
        private void Converter(string directory)
        {
            var             ffmpeg          = new FFMpegConverter();
            ConvertSettings convertSettings = new ConvertSettings()
            {
                CustomOutputArgs = "-s 320x240 -b:v 128k -bufsize 128k "
            };
            var fileOutput = String.Concat(System.IO.Path.GetDirectoryName(directory), "/", System.IO.Path.GetFileNameWithoutExtension(directory), "2.mp4");

            ffmpeg.ConvertMedia(directory, Format.mov, fileOutput, Format.mp4, convertSettings);
        }
コード例 #20
0
ファイル: FTP_controller.cs プロジェクト: pepies/coft
 /// <summary>
 /// Convert .asf to .mp4
 /// </summary>
 /// <param name="id"></param>
 private static void convert(String id)
 {
     try {
         String OutputPath = "./" + video.folder + "/" + id + ".mp4";
         String AsfPath    = "./" + video.folder + "/" + id + ".asf";
         var    ffMpeg     = new FFMpegConverter();
         ffMpeg.ConvertMedia(AsfPath, OutputPath, Format.mp4);
     }catch (FFMpegException f) {
         Achp.i.myConsoleWrite("konverzia: " + f.Message);
         Achp.i.myConsoleWrite("Prosím zvolte iný kodek kamery! - chybné videá budú zmazané.");
     }
 }
コード例 #21
0
        static void ConvertMedia()
        {
            FFMpegConverter ffMpeg  = new FFMpegConverter();
            ConvertSettings setting = new ConvertSettings();

            setting.CustomOutputArgs = " -threads 2";   // 以两个线程进行运行,加快处理的速度
            for (int i = 0; i < 100; i++)
            {
                ffMpeg.ConvertMedia("1.amr", "2.mp3", "MP3");  // 将h5不支持的视频转换为支持的视频
                Console.WriteLine(i);
            }
        }
コード例 #22
0
ファイル: EditController.cs プロジェクト: Ernest96/SM
        public ActionResult VideoConvert(HttpPostedFileBase video, string toFormat)
        {
            string path    = HttpContext.Server.MapPath("~/Content/" + video.FileName);
            string outpath = HttpContext.Server.MapPath("~/Content/video." + toFormat);
            var    ffMpeg  = new FFMpegConverter();
            var    set     = new ConvertSettings()
            {
                CustomOutputArgs = "-b 4000k -minrate 4000k -maxrate 4000k"
            };

            video.SaveAs(path);

            switch (toFormat)
            {
            case "mp4":
                ffMpeg.ConvertMedia(path, null, outpath, Format.mp4, set);
                break;

            case "avi":
                ffMpeg.ConvertMedia(path, null, outpath, Format.avi, set);
                break;

            case "wmv":
                ffMpeg.ConvertMedia(path, null, outpath, Format.wmv, set);
                break;

            case "mkv":
                ffMpeg.ConvertMedia(path, null, outpath, Format.matroska, set);
                break;

            case "mov":
                ffMpeg.ConvertMedia(path, null, outpath, Format.mov, set);
                break;

            default:
                return(Content(""));
            }

            return(Json(new { succes = true, link = "http://sm.com/Content/video." + toFormat }));
        }
コード例 #23
0
            public void doAction()
            {
                FFMpegConverter ffMpeg = new FFMpegConverter();

                //Call Builder methods here - get settings
                ffMpeg.ConvertMedia(
                    mInFile,
                    "mp4",
                    mOutFile,
                    "mp3",
                    settings
                    );
            }
コード例 #24
0
ファイル: MusicExport.cs プロジェクト: CaspervdB/musicPlayer
        public async Task SaveAudioToDiskAsync(string link, Playlist playList)
        {
            string source = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, @"music\");

            playList.PlaylistName += @"\"; //playlistname is the foldername
            YoutubeClient youtube = new YoutubeClient();
            Video         video   = await youtube.Videos.GetAsync(link);

            string         legalTitle     = string.Join("", video.Title.Split(Path.GetInvalidFileNameChars())); // Removes all possible illegal filename characetrs from the title
            StreamManifest streamManifest = await youtube.Videos.Streams.GetManifestAsync(link);

            IStreamInfo streamInfo = streamManifest.GetAudioOnly().WithHighestBitrate();

            if (streamInfo != null)
            {
                // Download the stream to file
                string fileName = $"{source + playList.PlaylistName + legalTitle}";

                await youtube.Videos.Streams.DownloadAsync(streamInfo, fileName + ".mp4"); //downloaden van mp4

                FFMpegConverter ffMpeg = new FFMpegConverter();
                ffMpeg.ConvertMedia(fileName + ".mp4", fileName + ".mp3", "mp3"); //converteren van mp4 naar mp3
                File.Delete(fileName + ".mp4");

                Song newSong = new Song(fileName + ".mp3"); //aanmaken van songobject
                newSong.ArtistName    = video.Author;       //zetten van de filetags
                newSong.SongTitle     = video.Title;
                newSong.AlbumTitle    = null;
                newSong.AlbumTrack    = 0;
                newSong.MaxAlbumTrack = 0;
                newSong.Year          = 0;
                newSong.BPM           = 0;
                /* downloaden van thumbnail*/
                using (WebClient client = new WebClient())
                {
                    client.DownloadFile(video.Thumbnails.HighResUrl, fileName + ".jpg");
                }

                newSong.setAlbumArt(fileName + ".jpg"); //zetten van albumart metadata

                File.Delete(fileName + ".jpg");         //deleten van thumbnail image file

                newSong.saveFileTag();                  //opslaan van filetags

                playList.addSong(newSong);

                //toevoegen aan database
                DbManager db = new DbManager();
                db.addSongToDatabase(newSong);
            }
        }
コード例 #25
0
 void ConvertirVideo(string video)
 {
     try
     {
         string path2       = Application.StartupPath;
         var    Convertidor = new FFMpegConverter();
         string nombre      = Guid.NewGuid().ToString().Substring(0, 8);
         Convertidor.ConvertMedia(video, nombre + ".mp4", "mp4");
     }
     catch (Exception ex)
     {
         MessageBox.Show("Este Video no se puede convertir: " + video + ex.Message);
     }
 }
コード例 #26
0
ファイル: Program.cs プロジェクト: NikkeArp/MediaConverter
        /// <summary>
        /// Converts files to target format. If logging
        /// is on, prints every file to console.
        /// </summary>
        /// <param name="filePaths"></param>
        private static void ConvertFiles(string[] filePaths)
        {
            FFMpegConverter converter = new FFMpegConverter();

            foreach (string file in filePaths)
            {
                string newFile = file.Substring(0, file.Length - _args.StartFormat.Length) + _args.TargetFormat;
                converter.ConvertMedia(file, newFile, _args.TargetFormat);
                if (_args.LogEachFile)
                {
                    string filename = file.Substring(file.LastIndexOf('\\') + 1);
                    _output.LogFileConversion(filename);
                }
            }
        }
コード例 #27
0
        public void Start()
        {
            InitSaveFile();

            var t = Task.Run(() => {
                try
                {
                    _converter.ConvertMedia("desktop", "gdigrab", _saveFileName, null, _settings);
                }
                catch (Exception ex)
                {
                    LogWrapper.Default.Fatal(ex);
                }
            });
        }
コード例 #28
0
        private async Task LoadSidebar()
        {
            List <SubtitleItem> subs = new List <SubtitleItem>();

            CurrentStatus.Text = "Loading info";
            await Task.Run(() => {
                FFProbe probe  = new FFProbe();
                probe.ToolPath = Environment.GetFolderPath(SpecialFolder.ApplicationData);
                var info       = probe.GetMediaInfo(scannedFile.NewName);
                var video      = info.Streams.Where(x => x.CodecType == "video").FirstOrDefault();
                var audio      = info.Streams.Where(x => x.CodecType == "audio").FirstOrDefault();
                Dispatcher.Invoke(() => {
                    EpisodeName.Text  = episode.episodeName;
                    SeriesNumber.Text = Helper.GenerateName(episode);
                    Framerate.Text    = "Framerate: " + video.FrameRate.ToString("##.##");
                    Resolution.Text   = "Resolution: " + video.Width + "x" + video.Height;
                    VideoCodec.Text   = "Video codec: " + video.CodecLongName;
                    PixelFormat.Text  = "Pixel format: " + video.PixelFormat;
                    AudioCodec.Text   = "Audio codec: " + audio.CodecLongName;
                });
                var multiple = info.Streams.Where(x => x.CodecType == "subtitle").Where(x => x.CodecName == "srt");
                var single   = multiple.FirstOrDefault();
                if (single != null)
                {
                    FFMpegConverter converter = new FFMpegConverter();
                    converter.FFMpegToolPath  = probe.ToolPath;
                    Stream str = new MemoryStream();
                    converter.ConvertMedia(scannedFile.NewName, str, "srt");
                    FoundSubtitle fs = new FoundSubtitle(str);
                    fs.Version       = "Packed with video";
                    allSubtitles.Add(fs);
                }
                else
                {
                    var subtitles = episode.files.Where(x => x.Type == ScannedFile.FileType.Subtitles);
                    foreach (var sub in subtitles)
                    {
                        FoundSubtitle fs = new FoundSubtitle(sub.NewName);
                        fs.Version       = sub.OriginalName;
                        allSubtitles.Add(fs);
                    }
                }
                LoadSideBarSubs();
            });

            CurrentStatus.Text = "";
            RenderSubs();
        }
コード例 #29
0
        private async Task Add(Discord.Commands.CommandEventArgs e)
        {
            await e.Message.Delete();

            if (playing && e.User.VoiceChannel != voiceChannel)
            {
                await e.Channel.SendMessage("Join vc NOW :angry:");

                return;
            }
            var param = e.GetArg("param");

            if (param.Length <= 0)
            {
                await e.Channel.SendMessage("I cannot add nothing to the queue");

                return;
            }
            try
            {
                var youTube = Client.For(YouTube.Default);         // starting point for YouTube actions
                var video   = youTube.GetVideo(e.GetArg("param")); // gets a Video object with info about the video
                var vidfile = Path.Combine(Environment.CurrentDirectory, "Music", video.FullName);
                Console.WriteLine(vidfile);
                var mp3file = Path.Combine(Environment.CurrentDirectory, "Music", video.Title + ".mp3");
                if (!File.Exists(mp3file))
                {
                    byte[] bytes = await video.GetBytesAsync();

                    File.WriteAllBytes(vidfile, bytes);
                    songcounter++;
                    videoconverter.ConvertMedia(vidfile, mp3file, "mp3");
                    File.Delete(vidfile);
                }
                queue.Add(new Song(mp3file, video.Title, e.User.Name));
                await e.Channel.SendMessage("**" + video.Title + "** has been added to the queue by *" + e.User.Name + "*!");

                MyBot.Log(DateTime.Now.ToUniversalTime().ToShortTimeString() + " - " + e.Channel.Name + ") Song added: " + video.FullName, e.Channel.Name + "_log");
            }
            catch (Exception ex)
            {
                await e.Channel.SendMessage("I could not download that...");

                Console.WriteLine(ex.StackTrace);
                return;
            }
            await Play(e);
        }
コード例 #30
0
        private void ConvertVideo(object NameVideo)
        {
            string Obj = NameVideo.ToString();

            string[] Str = Obj.Split('\n').ToArray();
            try
            {
                ffMpeg.ConvertMedia(Str[0] + "\\" + Str[1], Format.mp4, PathConvert + Str[1], NReco.VideoConverter.Format.mp4, ffMpegSettings);
            }
            catch
            {
                //System.Windows.Forms.MessageBox.Show("Wrong video format - " + Str[1] + ". Use .mp4 videos please");
                //if (File.Exists(PathConvert + Str[1])) File.Delete(PathConvert + Str[1]);
                //Form1.DeviceName = "";
            }
        }
コード例 #31
0
        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);
        }
コード例 #32
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;
                }
            }
        }
コード例 #33
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;
                }
            }
        }
コード例 #34
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);
        }
コード例 #35
-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;
        }
コード例 #36
-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);
        }
コード例 #37
-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();
        }
コード例 #38
-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");
            }
        }
コード例 #39
-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;
            }
        }
コード例 #40
-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");
        }