FFmpeg 是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。采用 LGPL 或 GPL 许可证。它提供了录制、转换以及流化音视频的完整解决方案。它包含了非常先进的音频/视频编解码库 libavcodec,为了保证高可移植性和编解码质量,libavcodec 里很多 code 都是从头开发的。
这篇文章主要介绍如何在 C# 中使用 FFmpeg。
在项目中使用包管理器控制台安装 nuget 包:
PM> Install-Package xFFmpeg.NET
1、从视频中抓取缩略图
var inputFile = new MediaFile (@"C:\Path\To_Video.flv"); var outputFile = new MediaFile (@"C:\Path\To_Save_Image.jpg"); var ffmpeg = new Engine("C:\\ffmpeg\\ffmpeg.exe"); // 保存位于视频第 15 秒的帧。 var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(15) }; await ffmpeg.GetThumbnailAsync(inputFile, outputFile, options);
2、获取视频元数据
var inputFile = new MediaFile (@"C:\Path\To_Video.flv"); var ffmpeg = new Engine("C:\\ffmpeg\\ffmpeg.exe"); var metadata = await ffmpeg.GetMetadataAsync(inputFile); Console.WriteLine(metadata.Duration);
3、基本转换
var inputFile = new MediaFile (@"C:\Path\To_Video.flv"); var outputFile = new MediaFile (@"C:\Path\To_Save_New_Video.mp4"); var ffmpeg = new Engine("C:\\ffmpeg\\ffmpeg.exe"); await ffmpeg.ConvertAsync(inputFile, outputFile);
4、将 Flash 视频转换为 DVD
var inputFile = new MediaFile (@"C:\Path\To_Video.flv"); var outputFile = new MediaFile (@"C:\Path\To_Save_New_DVD.vob"); var conversionOptions = new ConversionOptions { Target = Target.DVD, TargetStandard = TargetStandard.PAL }; var ffmpeg = new Engine("C:\\ffmpeg\\ffmpeg.exe"); await ffmpeg.ConvertAsync(inputFile, outputFile, conversionOptions);
5、将 FLV 转换为 MP4
var inputFile = new MediaFile (@"C:\Path\To_Video.flv"); var outputFile = new MediaFile (@"C:\Path\To_Save_New_Video.mp4"); var conversionOptions = new ConversionOptions { MaxVideoDuration = TimeSpan.FromSeconds(30), VideoAspectRatio = VideoAspectRatio.R16_9, VideoSize = VideoSize.Hd1080, AudioSampleRate = AudioSampleRate.Hz44100 }; var ffmpeg = new Engine("C:\\ffmpeg\\ffmpeg.exe"); await ffmpeg.ConvertAsync(inputFile, outputFile, conversionOptions);
6、截取视频
var inputFile = new MediaFile (@"C:\Path\To_Video.flv"); var outputFile = new MediaFile (@"C:\Path\To_Save_ExtractedVideo.flv"); var ffmpeg = new Engine("C:\\ffmpeg\\ffmpeg.exe"); var options = new ConversionOptions(); options.CutMedia(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(25)); await ffmpeg.ConvertAsync(inputFile, outputFile, options);
以上就是 FFmpeg.NET 类库才常用操作。