private void startScreenCapBtn_Click(object sender, EventArgs e)//开始屏幕录制 { if (savePath == null) { MessageBox.Show("请先选择文件保存路径!"); return; } this.stopScreenCapBtn.Enabled = true; f = new Ffmpeg(); string time = DateTime.Now.ToString(); // 2008-9-4 20:02:10 if (soundSource != null) { command = "-f gdigrab -i desktop -f dshow -i audio=" + "\"" + soundSource + "\"" + " -r 5 -vcodec libx264 -preset:v ultrafast -tune:v zerolatency -acodec libmp3lame " + savePath; //command = "-f gdigrab -i desktop -f dshow -i audio=" + "\"" + soundSource + "\""+" -r 5 -acodec libmp3lame -f mpegts "+savePath+ } else { command = "-f gdigrab -i desktop -r 5 -vcodec libx264 -preset:v ultrafast " + savePath; } //MessageBox.Show(command); try { // f.execute(command); f.beginExecute(command); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } }
private void RetryRecord() { if (Ffmpeg == null || Task == null) { Debug.WriteLine("RecObj was not initialized!"); return; } if (CommonFunc.CheckChannelLinkValid(Channel, ChannelLink)) { Status = RecordStatus.Recording; Ffmpeg.StartRecord(Channel, ChannelLink, Duration * 60, RetryTimes); Finish(); } else { DateTime temp_starttime = GetRetryStartTime(); if (IsNearTheEndTime(temp_starttime)) { Status = RecordStatus.Failed; } else { StartTime = temp_starttime; Duration = GetRetryDuration(StartTime, EndTime); Initialization(); } } }
static async Task Main(string[] args) { var config = new ConfigurationBuilder().AddCommandLine(args) .AddJsonFile("appsettings.json") .Build(); var entryAssembly = Assembly.GetEntryAssembly(); var executingDirectory = Path.GetDirectoryName(entryAssembly.Location); var userId = config["u"]; var password = config["p"]; var downloadDirectory = config["downloadDirectory"]; var serviceOption = ServiceOption.FromConfiguration(config); var ffmpeg = new Ffmpeg(Path.Combine(executingDirectory, "ffmpeg.exe")); var client = new ServiceClient(serviceOption, ffmpeg); await client.LoginAsync(userId, password); var video = await client.GetVideoAsync(); var filePath = Path.Combine(downloadDirectory, video.FileName); if (!File.Exists(filePath)) { await video.DownloadToAsync(filePath); } }
public async Task <ExtractResult> GifExtractRemote(double start, double end, string subs) { var streams = await Ydl.GetAVStreamUrlsAsync(CurrentMediaElement.Id); if (streams == null) { return(new ExtractResult(false, "Youtube-dl failed to get av streams")); } var htmlCtrl = ContentEx.GetFirstHtmlCtrl(); var refs = htmlCtrl?.GetReferences(); var filename = $"{refs?.Title ?? CurrentMediaElement.Id}-{start}-{end}"; var filepath = MediaPlayerFilesystem.ImageDir.CombineFile(filename).FullPath; if (!await Ffmpeg.GifExtract(streams.Video, start, end, filepath)) { return(new ExtractResult(false, "Ffmpeg failed to create gif extract")); } List <ContentBase> contents = new List <ContentBase>(); var htmlContent = subs ?? string.Empty; htmlContent += "\r\n"; htmlContent += $"<img href='{filepath}'>"; var mainHtml = new TextContent(true, htmlContent); contents.Add(mainHtml); refs.Title += $": Gif Extract - {start} -> {end}"; // TODO: Convert to human readable var priority = MediaPlayerState.Instance.Config.DefaultExtractPriority; var res = ContentEx.CreateSMElement(ExpectedElementId, priority, contents, refs, false); return(new ExtractResult(res == CreationResult.Ok, res.Name())); }
public void FlushScreenBuffer() { //切换到新buffer var newBuffer = new MemoryBuffer(DateTime.Now); var b = buffer; buffer = newBuffer; //加入flushing lock (flushing) { flushing.Add(b); } var path = getFileName(b.StartTime); var folder = Path.GetDirectoryName(path); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } new Thread(() => { Ffmpeg.Save(getFileName(b.StartTime), b.Frames.ToArray()); lock (flushing) { flushing.Remove(b); } }) { Priority = ThreadPriority.BelowNormal, IsBackground = false }.Start(); }
private void button1_Click(object sender, EventArgs e) { var checkedButton = groupBox1.Controls.OfType <RadioButton>() .FirstOrDefault(r => r.Checked); Ffmpeg.Enviarcmd($"ffmpeg -i {ruta} C:\\Users\\Sergio\\Desktop\\video nuevo{checkedButton.Text}"); }
public string GetLog() { if (Ffmpeg != null) { Log = Ffmpeg.GetLog(); } return(Log); }
private void StartScreenshot(MetadataServiceConfigurator serviceConfigurator, string[] filePathes) { int count = 0; double avgEncodeFps = 0; var errorVideos = new List <string>(); var allSw = new Stopwatch(); var decodeSw = new Stopwatch(); foreach (string filePath in filePathes) { allSw.Restart(); Trace.WriteLine(String.Format("\n-------------Start decode file: {0}-------------\n", filePath)); try { string destinationFileName = GetDestinationFileName(filePath); var mediaInfo = new MediaInfoWrapper(); var metadataInfo = new VideoMetadataInfo(mediaInfo); VideoMediaInfo metadata = metadataInfo.GetMetadata(filePath); var metadataService = new MetadataService(serviceConfigurator, metadata); var stringBuilder = new FfmpegService(metadataService, filePath, _destinationPath, destinationFileName); var ffmpeg = new Ffmpeg(stringBuilder); string ffmpegString = stringBuilder.GetStringForScreenshot(); WriteFileInfo(ffmpegString, metadata); decodeSw.Restart(); ffmpeg.StartScreenshotProcess(); allSw.Stop(); decodeSw.Stop(); WriteFinishProcess(decodeSw.Elapsed, allSw.Elapsed, ffmpeg.EncodeFps); avgEncodeFps += ffmpeg.EncodeFps; count++; } catch (MediaFormatException ex) { string errorMessage = String.Format("Error File:\t\t{0}.\nError Param:\t\t{1}", filePath, ex.Message); Trace.WriteLine(errorMessage); errorVideos.Add(errorMessage); } catch (ExternalProcessException ex) { string errorMessage = String.Format("Error File:\t\t{0}.\nFfmpeg return:\t\t{1}\n{2}", filePath, ex.Result, ex.Arguments); Trace.WriteLine(errorMessage); errorVideos.Add(errorMessage); } finally { Trace.WriteLine(String.Format("\n-------------Finish decode file: {0}-------------\n", filePath)); } } avgEncodeFps = avgEncodeFps / count; WriteFinishInfo(avgEncodeFps, count, errorVideos); }
public ffmpegTest() { InitializeComponent(); videoPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Videos"); if (!Directory.Exists(videoPath)) { Directory.CreateDirectory(videoPath); } _ffmpeg = new Ffmpeg(); }
private void EncodeAndSave() { print("SCREENRECORDER IO THREAD STARTED"); while (threadIsProcessing) { if (frameQueue.Count > 0) { // Generate file path string path = GetFileFullName(savingFrameNumber.ToString()); // Dequeue the frame, encode it as a bitmap, and write it to the file using (FileStream fileStream = new FileStream(path, FileMode.Create)) { BitmapEncoder.WriteBitmap(fileStream, screenWidth, screenHeight, frameQueue.Dequeue()); fileStream.Close(); } // Done savingFrameNumber++; print("Saved " + savingFrameNumber + " frames. " + frameQueue.Count + " frames remaining."); } else { if (terminateThreadWhenDone) { break; } Thread.Sleep(1); } } terminateThreadWhenDone = false; threadIsProcessing = false; if (!string.IsNullOrEmpty(FFmpegToolPath)) { var ffmpeg = new Ffmpeg(FFmpegToolPath, persistentDataPath); ffmpeg.FrameRate = frameRate; ffmpeg.InputFileName = GetFileFullName("%d"); ffmpeg.Run(); print("Deleting files..."); var dir = new DirectoryInfo(persistentDataPath); var files = dir.GetFiles(); foreach (var f in files) { File.Delete(f.FullName); } } print("SCREENRECORDER IO THREAD FINISHED"); }
public void 正常系_動画の長さを取得() { FfmpegWrapper.Ffmpeg ffmpeg = new Ffmpeg(); string appdir = AppDomain.CurrentDomain.BaseDirectory; string InputFilePath = Path.Combine(appdir, "test.wmv"); int duration = ffmpeg.GetVideoDuration(InputFilePath); Assert.IsTrue(duration == 30); }
private void Record() { if (Ffmpeg == null || Task == null) { Debug.WriteLine("RecObj was not initialized!"); return; } Status = RecordStatus.Recording; Ffmpeg.StartRecord(Channel, ChannelLink, Duration * 60, RetryTimes); Finish(); }
public void Dispose() { Debug.WriteLine("RecObj Dispose."); if (Ffmpeg != null) { Ffmpeg.Dispose(); Ffmpeg = null; } if (Task != null) { Task.Dispose(); Task = null; } }
private void Finish() { if (!IsStoppedManually && IsEndEarlier()) { AddRetryRecord(); Status = (Ffmpeg.IsFIleExist()) ? RecordStatus.EndEarlier : RecordStatus.Failed; } else { Status = (Ffmpeg.IsFIleExist()) ? RecordStatus.Completed : RecordStatus.Failed; } GetLog(); Dispose(); }
public void 正常系_0秒から10秒分だけトリミングして保存() { FfmpegWrapper.Ffmpeg ffmpeg = new Ffmpeg(); string appdir = AppDomain.CurrentDomain.BaseDirectory; string InputFilePath = Path.Combine(appdir, "test.wmv"); string OutputFilePath = Path.Combine(appdir, Ffmpeg.SubFileName(InputFilePath, 2)); int start = 0; int duration = 5; ffmpeg.Triming(InputFilePath, OutputFilePath, start, duration); Assert.IsTrue(File.Exists(InputFilePath)); Assert.IsTrue(File.Exists(OutputFilePath)); }
public static void Main(string[] args) { using (Ffmpeg ffmpeg = new Ffmpeg(@"/usr/local/bin/ffmpeg")) { ffmpeg.OnProgress += (sender, eventArgs) => { Console.Write("Processing... {0} {1} Kb \r", eventArgs.Time.ToString(@"hh\:mm\:ss\.ff"), eventArgs.Size / 1024); }; Console.WriteLine("FfmpegSharp Test App\n"); Console.WriteLine("File Information"); MediaInfo mediaInfo = ffmpeg.GetInfo("big_buck_bunny_1080p_h264.mov"); Console.WriteLine(mediaInfo); Console.WriteLine("Simple Conversion"); try { OutputFile outFile = new OutputFile("Big Buck Bunny.mp4"); outFile.Video.Codec = "libx264"; outFile.Video.CustomArgs["crf"] = "25"; outFile.Video.CustomArgs["preset"] = "veryfast"; ffmpeg.OverwriteOutput = true; ffmpeg.Process("big_buck_bunny_1080p_h264.mov", outFile); //ffmpeg.Process("big_buck_bunny_1080p_h264.mov", "Big Buck Bunny.mp4"); } catch (FfmpegException ex) { Console.WriteLine(ex.Message); } Console.WriteLine("\n" + ffmpeg.LastCommand); Console.WriteLine("\nConversion finished"); //Console.ReadKey(); } }
void GenerateThumbnail(Ffmpeg ffmpeg, string localSourceFile, string localThumbnailFile, MovieMetadata mm) { ffmpeg.ExtractFrame(localSourceFile, localThumbnailFile, GetThumbnailSeconds(mm)); using (var wand = new MagickWand(localThumbnailFile)) { wand.GetLargestDimensionsKeepingAspectRatio(THUMB_WIDTH, THUMB_HEIGHT, out uint width, out uint height); wand.ScaleImage(width, height); // sharpen after potentially resizing // http://www.imagemagick.org/Usage/resize/#resize_unsharp wand.UnsharpMaskImage(0, 0.7, 0.7, 0.008); wand.WriteImage(localThumbnailFile, true); mm.ThumbHeight = (int)height; mm.ThumbWidth = (int)width; } }
void GenerateThumbSq(Ffmpeg ffmpeg, string localSourceFile, string localThumbSqFile, MovieMetadata mm) { ffmpeg.ExtractFrame(localSourceFile, localThumbSqFile, GetThumbnailSeconds(mm)); using (var wand = new MagickWand(localThumbSqFile)) { var width = (double)wand.ImageWidth; var height = (double)wand.ImageHeight; var aspect = width / height; if (aspect >= THUMB_SQ_ASPECT) { var newWidth = (width / height) * THUMB_SQ_HEIGHT; // scale image to final height wand.ScaleImage((uint)newWidth, THUMB_SQ_HEIGHT); // crop sides as needed wand.CropImage(THUMB_SQ_WIDTH, THUMB_SQ_HEIGHT, (int)(newWidth - THUMB_SQ_WIDTH) / 2, 0); } else { var newHeight = THUMB_SQ_WIDTH / (width / height); // scale image to final width wand.ScaleImage(THUMB_SQ_WIDTH, (uint)newHeight); // crop top and bottom as needed wand.CropImage(THUMB_SQ_WIDTH, THUMB_SQ_HEIGHT, 0, (int)(newHeight - THUMB_SQ_HEIGHT) / 2); } // sharpen after potentially resizing // http://www.imagemagick.org/Usage/resize/#resize_unsharp wand.UnsharpMaskImage(0, 0.7, 0.7, 0.008); wand.WriteImage(localThumbSqFile, true); mm.ThumbSqHeight = THUMB_SQ_HEIGHT; mm.ThumbSqWidth = THUMB_SQ_WIDTH; } }
private void StartEncode(MetadataServiceConfigurator serviceConfigurator, string[] filePathes) { var allSw = new Stopwatch(); var decodeSw = new Stopwatch(); foreach (var filePath in filePathes) { allSw.Start(); Trace.WriteLine(String.Format("\n-------------Start decode file: {0}-------------\n", filePath)); try { var destinationFilePath = GetDestinationFilePath(filePath); var mediaInfo = new MediaInfoWrapper(); var metadataInfo = new VideoMetadataInfo(mediaInfo); var metadata = metadataInfo.GetMetadata(filePath); var metadataService = new MetadataService(serviceConfigurator, metadata); var stringBuilder = new FfmpegStringBuilder(metadataService, destinationFilePath); var ffmpeg = new Ffmpeg(stringBuilder); var ffmpegString = stringBuilder.GetStringForEncoder(); WriteFileInfo(ffmpegString, metadata); decodeSw.Start(); var result = ffmpeg.StartEncodeProcess(); allSw.Stop(); decodeSw.Stop(); WriteFinishProcess(decodeSw.Elapsed, allSw.Elapsed, result); } catch (MediaFormatException ex) { Trace.WriteLine(String.Format("Error File: {0}. Error Param: {1}", ex.VideoUri, ex.InvalidParameter)); } finally { Trace.WriteLine(String.Format("\n-------------Finish decode file: {0}-------------\n", filePath)); } } }
private void StartEncode(MetadataServiceConfigurator serviceConfigurator, string[] filePathes, string prefix = "") { int count = 0; int excelStrCount = 2; double avgEncodeFps = 0; var errorVideos = new List <string>(); var allSw = new Stopwatch(); var decodeSw = new Stopwatch(); Excel excel = CreateExcel(); foreach (string filePath in filePathes) { allSw.Restart(); Trace.WriteLine(String.Format("\n-------------Start decode file: {0}-------------\n", filePath)); try { string destinationFileName = GetDestinationFileName(filePath, prefix); var mediaInfo = new MediaInfoWrapper(); var metadataInfo = new VideoMetadataInfo(mediaInfo); VideoMediaInfo metadata = metadataInfo.GetMetadata(filePath); var metadataService = new MetadataService(serviceConfigurator, metadata); var stringBuilder = new FfmpegService(metadataService, filePath, _destinationPath, destinationFileName); var ffmpeg = new Ffmpeg(stringBuilder); string ffmpegString = stringBuilder.GetStringForEncoder(); WriteFileInfo(ffmpegString, metadata); decodeSw.Restart(); ffmpeg.StartEncodeProcess(); allSw.Stop(); decodeSw.Stop(); WriteFinishProcess(decodeSw.Elapsed, allSw.Elapsed, ffmpeg.EncodeFps); if (ffmpeg.EncodeFps > 0) { SetExcelLine(excel, metadata, filePath, excelStrCount, ffmpeg.EncodeFps); excelStrCount++; } avgEncodeFps += ffmpeg.EncodeFps; count++; } catch (MediaFormatException ex) { string errorMessage = String.Format("Error File:\t\t{0}.\nError Param:\t\t{1}", filePath, ex.Message); Trace.WriteLine(errorMessage); errorVideos.Add(errorMessage); } catch (ExternalProcessException ex) { string errorMessage = String.Format("Error File:\t\t{0}.\nFfmpeg return:\t\t{1}\n{2}", filePath, ex.Result, ex.Arguments); Trace.WriteLine(errorMessage); errorVideos.Add(errorMessage); } finally { Trace.WriteLine(String.Format("\n-------------Finish decode file: {0}-------------\n", filePath)); } } excel.SaveDocument(String.Format(@"{0}\{1}_{2}.xlsx", _destinationPath, serviceConfigurator.Container, DateTime.Now.ToString("u").Replace(":", "-"))); excel.CloseDocument(); avgEncodeFps = avgEncodeFps / count; WriteFinishInfo(avgEncodeFps, count, errorVideos); }
public async Task <IActionResult> PostSoundCloud([FromBody] RequestBody requestBody) { var requestIp = Request.HttpContext.Connection.RemoteIpAddress; _logger.Information(string.Join(" ", requestIp, _logMessages["requestReceived"])); if (string.IsNullOrEmpty(requestBody.clientId) || string.IsNullOrEmpty(requestBody.soundcloudUrl.ToString())) { _logger.Information(string.Join(" ", requestIp, _logMessages["requestMalformed"])); return(StatusCode(400, new ErrorResponse(_logMessages["requestMalformed"]))); } var soundCloudManager = new Manager.Methods.SoundCloud(); var createdFiles = new List <string>(); try { if (requestBody.soundcloudUrl.ToString().Contains("sets")) //Use regex later { _logger.Information(string.Join(" ", requestIp, _logMessages["requestPlaylist"])); var playlistInformation = soundCloudManager.ResolvePlaylistUrl(requestBody.soundcloudUrl, requestBody.clientId); _logger.Information(string.Join(" ", requestIp, _logMessages["requestAuthentication"])); var playlistFolder = Directory.CreateDirectory($"{_tempFileStore}\\{playlistInformation.Title}"); _logger.Information(string.Join(" ", requestIp, _logMessages["playlistInformation"])); foreach (var track in playlistInformation.Tracks) { var trackUrl = soundCloudManager.QueryTrackUrl(track.Id, requestBody.clientId); var trackInformation = soundCloudManager.ResolveTrackUrl(trackUrl, requestBody.clientId); var trackName = trackInformation.Title; var trackMediaUrl = soundCloudManager.QueryTrackTranscodings(trackInformation.Media.Transcodings, requestBody.clientId); var filePath = $"{_tempFileStore}\\{playlistInformation.Title}\\{trackName}.mp3"; var trackM3u8 = soundCloudManager.QueryTrackM3u8(trackMediaUrl); var ffmpegManager = new Ffmpeg(); await ffmpegManager.DownloadTrack(trackM3u8, filePath); _logger.Information(string.Join(" ", requestIp, _logMessages["fileDownloadPlaylist"])); var trackMediaInformationMod = new TrackInformationMod() { artist = trackInformation.User.Username, album = trackInformation.User.Username, title = trackInformation.Title }; var id3Manager = new Id3(); id3Manager.SetFileMetadata(filePath, trackMediaInformationMod); } string zipPath = $"{_tempFileStore}\\{playlistInformation.Title}.zip"; var compressionManager = new Compression(); compressionManager.CompressFolder(playlistFolder.FullName, zipPath); _logger.Information(string.Join(" ", requestIp, _logMessages["zipStatus"])); var fileStream = await System.IO.File.ReadAllBytesAsync(zipPath); Response.Headers.Add("File-Type", "zip"); createdFiles.Add(zipPath); createdFiles.Add(playlistFolder.FullName); return(File(fileStream, "application/octet-stream")); } else { var trackInformation = soundCloudManager.ResolveTrackUrl(requestBody.soundcloudUrl, requestBody.clientId); _logger.Information(string.Join(" ", requestIp, _logMessages["requestAuthentication"])); string trackName = trackInformation.Title; var trackMediaInformation = soundCloudManager.QueryTrackTranscodings(trackInformation.Media.Transcodings, requestBody.clientId); var trackMediaUrl = soundCloudManager.QueryTrackM3u8(trackMediaInformation); string filePath = $"{_tempFileStore}\\{trackName}.mp3"; var ffmpegManager = new Ffmpeg(); await ffmpegManager.DownloadTrack(trackMediaUrl, filePath); _logger.Information(string.Join(" ", requestIp, _logMessages["fileDownload"])); var trackMediaInformationMod = new TrackInformationMod() { artist = trackInformation.User.Username, album = trackInformation.User.Username, title = trackInformation.Title }; var id3Manager = new Id3(); id3Manager.SetFileMetadata(filePath, trackMediaInformationMod); var fileStream = await System.IO.File.ReadAllBytesAsync(filePath); _logger.Information(string.Join(" ", requestIp, _logMessages["requestSuccess"])); Response.Headers.Add("File-Type", "mp3"); return(File(fileStream, "application/octet-stream")); } } catch (Exception processException) { _logger.Information(string.Join(" ", requestIp, _logMessages["requestError"], processException.Message)); return(StatusCode(500, new ErrorResponse(processException.Message))); } finally { foreach (var file in createdFiles) { if (Directory.Exists(file)) { Directory.Delete(file, true); } else { System.IO.File.Delete(file); } } //Leaves still some unknow file behind when downloading singular Tracks... _logger.Information(string.Join(" ", requestIp, _logMessages["fileCleanup"])); } }
private void StartScreenshot(MetadataServiceConfigurator serviceConfigurator, string[] filePathes) { int count = 0; double avgEncodeFps = 0; var errorVideos = new List<string>(); var allSw = new Stopwatch(); var decodeSw = new Stopwatch(); foreach (string filePath in filePathes) { allSw.Restart(); Trace.WriteLine(String.Format("\n-------------Start decode file: {0}-------------\n", filePath)); try { string destinationFileName = GetDestinationFileName(filePath); var mediaInfo = new MediaInfoWrapper(); var metadataInfo = new VideoMetadataInfo(mediaInfo); VideoMediaInfo metadata = metadataInfo.GetMetadata(filePath); var metadataService = new MetadataService(serviceConfigurator, metadata); var stringBuilder = new FfmpegService(metadataService, filePath, _destinationPath, destinationFileName); var ffmpeg = new Ffmpeg(stringBuilder); string ffmpegString = stringBuilder.GetStringForScreenshot(); WriteFileInfo(ffmpegString, metadata); decodeSw.Restart(); ffmpeg.StartScreenshotProcess(); allSw.Stop(); decodeSw.Stop(); WriteFinishProcess(decodeSw.Elapsed, allSw.Elapsed, ffmpeg.EncodeFps); avgEncodeFps += ffmpeg.EncodeFps; count++; } catch (MediaFormatException ex) { string errorMessage = String.Format("Error File:\t\t{0}.\nError Param:\t\t{1}", filePath, ex.Message); Trace.WriteLine(errorMessage); errorVideos.Add(errorMessage); } catch (ExternalProcessException ex) { string errorMessage = String.Format("Error File:\t\t{0}.\nFfmpeg return:\t\t{1}\n{2}", filePath, ex.Result, ex.Arguments); Trace.WriteLine(errorMessage); errorVideos.Add(errorMessage); } finally { Trace.WriteLine(String.Format("\n-------------Finish decode file: {0}-------------\n", filePath)); } } avgEncodeFps = avgEncodeFps/count; WriteFinishInfo(avgEncodeFps, count, errorVideos); }
private void StartEncode(MetadataServiceConfigurator serviceConfigurator, string[] filePathes, string prefix = "") { int count = 0; int excelStrCount = 2; double avgEncodeFps = 0; var errorVideos = new List<string>(); var allSw = new Stopwatch(); var decodeSw = new Stopwatch(); Excel excel = CreateExcel(); foreach (string filePath in filePathes) { allSw.Restart(); Trace.WriteLine(String.Format("\n-------------Start decode file: {0}-------------\n", filePath)); try { string destinationFileName = GetDestinationFileName(filePath, prefix); var mediaInfo = new MediaInfoWrapper(); var metadataInfo = new VideoMetadataInfo(mediaInfo); VideoMediaInfo metadata = metadataInfo.GetMetadata(filePath); var metadataService = new MetadataService(serviceConfigurator, metadata); var stringBuilder = new FfmpegService(metadataService, filePath, _destinationPath, destinationFileName); var ffmpeg = new Ffmpeg(stringBuilder); string ffmpegString = stringBuilder.GetStringForEncoder(); WriteFileInfo(ffmpegString, metadata); decodeSw.Restart(); ffmpeg.StartEncodeProcess(); allSw.Stop(); decodeSw.Stop(); WriteFinishProcess(decodeSw.Elapsed, allSw.Elapsed, ffmpeg.EncodeFps); if (ffmpeg.EncodeFps > 0) { SetExcelLine(excel, metadata, filePath, excelStrCount, ffmpeg.EncodeFps); excelStrCount++; } avgEncodeFps += ffmpeg.EncodeFps; count++; } catch (MediaFormatException ex) { string errorMessage = String.Format("Error File:\t\t{0}.\nError Param:\t\t{1}", filePath, ex.Message); Trace.WriteLine(errorMessage); errorVideos.Add(errorMessage); } catch (ExternalProcessException ex) { string errorMessage = String.Format("Error File:\t\t{0}.\nFfmpeg return:\t\t{1}\n{2}", filePath, ex.Result, ex.Arguments); Trace.WriteLine(errorMessage); errorVideos.Add(errorMessage); } finally { Trace.WriteLine(String.Format("\n-------------Finish decode file: {0}-------------\n", filePath)); } } excel.SaveDocument(String.Format(@"{0}\{1}_{2}.xlsx", _destinationPath, serviceConfigurator.Container, DateTime.Now.ToString("u").Replace(":", "-"))); excel.CloseDocument(); avgEncodeFps = avgEncodeFps/count; WriteFinishInfo(avgEncodeFps, count, errorVideos); }
private void extraerImagenesExportar_Click(object sender, EventArgs e) { Ffmpeg.extraerImagenes(ruta, archivo, textBoxExtraerImagenes.Text); }
private void QuitarAudioExportar_Click(object sender, EventArgs e) { Ffmpeg.quitarAudio(ruta, archivo); }
private void cambiarFormatoExportar_Click(object sender, EventArgs e) { String formato = cambiarFormatoBox.Controls.OfType <RadioButton>().FirstOrDefault(r => r.Checked).Text; Ffmpeg.cambiarFormato(ruta, archivo, formato); }
private void resolucionExportar_Click(object sender, EventArgs e) { Ffmpeg.cambiarResolucion(ruta, archivo, TextBoxResolucionX.Text, TextBoxResolucionY.Text); }
private void button5_Click(object sender, EventArgs e) { Ffmpeg.Enviarcmd($"ffmpeg -i {ruta} -c copy -an C:\\Users\\Sergio\\Desktop\\song_sinaudio.mp4"); }
private static void EnsureFfmpegDependency(Ffmpeg ffmpeg) { Console.WriteLine("Finding or downloading ffmpeg"); ffmpeg.EnsureExists(); }
public FfmpegTest() { Ffmpeg = new Ffmpeg(new HttpClient()); CleanDefaultFilePath(); }
//****************************************************// /// <summary> /// (非同期) トリミング処理 /// </summary> /// <param name="TargetFilePath"></param> /// <param name="duration"></param> /// <returns></returns> public void RunTriming(string TargetFilePath, int duration, bool OverwriteFlg) { string InputFilePath = TargetFilePath; int total_duration = ffmpeg.GetVideoDuration(TargetFilePath); // 例外処理 if (duration > total_duration) { WriteConsole("ファイルの時間が指定した切り取り時間よりも短いです。", FontColors.RED); return; } // Make Sub dir string SubDir = Path.Combine(Path.GetDirectoryName(InputFilePath), Path.GetFileNameWithoutExtension(InputFilePath)); Directory.CreateDirectory(SubDir); // 切り出す動画の数 int N = Convert.ToInt32(Math.Ceiling((double)total_duration / duration)); for (int i = 1; i <= N; i++) { // キャンセル処理 if (this.Cancel == true) { WriteConsole($"[CANCEL] サブジョブが、キャンセルされました", FontColors.RED); this.Cancel = false; return; } // プログレスバーの表示 string QuesProgressBar = ""; for (int j = 1; j <= (N - i); j++) { QuesProgressBar += "|"; } WriteConsole($"[TRIMING] {QuesProgressBar}", FontColors.GREEN); // 入出力の設定 string _OutFilePath = Ffmpeg.SubFileName(InputFilePath, i); string _OutFileName = Path.GetFileName(_OutFilePath); string NewOutFilePath = Path.Combine(SubDir, _OutFileName); int start = (i - 1) * duration; WriteConsole($"[TRIMING] Start:{start}s, Duration:{duration}s, Total:{total_duration}s"); // 出力ファイルの有無 if (File.Exists(NewOutFilePath)) { // 出力ファイルがある場合 if (OverwriteFlg) { // 上書きします ffmpeg.Triming(InputFilePath, NewOutFilePath, start, duration); } else { // ファイルが存在しており, 上書きしない WriteConsole($"[TRIMING] ファイルが存在します. 上書きしません."); } } else { // ない場合 新しく作ります ffmpeg.Triming(InputFilePath, NewOutFilePath, start, duration); } } }
public void StopRecord() { IsStoppedManually = true; Status = RecordStatus.Stopping; Ffmpeg.StopRecord(); }