
FFMpegCore 是一个 .NET Standard 的 FFMpeg/FFProbe 封装库,用于轻松将媒体分析和转换功能集成到应用程序中。支持同步和异步调用。
第一步,老规矩,先安装
Install-Package FFMpegCoreFFMpegCore 库本身并不包含 FFmpeg 可执行文件,因此需要在你的应用程序中指定 FFmpeg 可执行文件的位置。你可以从 FFmpeg 官方网站 下载适合你操作系统的版本。
下载完成后,将 ffmpeg.exe(Windows)或 ffmpeg(Linux/Mac)放到一个文件夹中,并在代码中设置 FFmpeg 可执行文件的路径。
// 设置全局选项
GlobalFFOptions.Configure(new FFOptions { BinaryFolder = "./ffmpeg", TemporaryFilesFolder = "/tmp" });
// 或单独设置每次运行的选项
await FFMpegArguments
.FromFileInput(inputPath)
.OutputToFile(outputPath)
.ProcessAsynchronously(true, new FFOptions { BinaryFolder = "./bin", TemporaryFilesFolder = "/tmp" });设置为资源或者始终复制到目录
<ItemGroup>
<Resource Include="ffmpeg\ffmpeg.exe" />
<Resource Include="ffmpeg\ffplay.exe" />
<Resource Include="ffmpeg\ffprobe.exe" />
</ItemGroup>或者通过创建 ffmpeg.config.json 文件来进行配置
{
"BinaryFolder": "./bin",
"TemporaryFilesFolder": "/tmp"
}使用 FFProbe 分析媒体文件:
var mediaInfo = await FFProbe.AnalyseAsync(inputPath);
// 或者
var mediaInfo = FFProbe.Analyse(inputPath);使用 FFMpeg 转换媒体文件:
FFMpegArguments
.FromFileInput(inputPath)
.OutputToFile(outputPath, false, options => options
.WithVideoCodec(VideoCodec.LibX264)
.WithConstantRateFactor(21)
.WithAudioCodec(AudioCodec.Aac)
.WithVariableBitrate(4)
.WithVideoFilters(filterOptions => filterOptions.Scale(VideoSize.Hd))
.WithFastStart())
.ProcessSynchronously();从流中转换或输出到流:
await FFMpegArguments
.FromPipeInput(new StreamPipeSource(inputStream))
.OutputToPipe(new StreamPipeSink(outputStream), options => options
.WithVideoCodec("vp9")
.ForceFormat("webm"))
.ProcessAsynchronously();提供的辅助方法可以轻松完成常见操作。
• 捕获快照
var bitmap = FFMpeg.Snapshot(inputPath, new Size(200, 400), TimeSpan.FromMinutes(1));
// 或将图像保存到磁盘
FFMpeg.Snapshot(inputPath, outputPath, new Size(200, 400), TimeSpan.FromMinutes(1));• 捕获 GIF 快照
await FFMpeg.GifSnapshotAsync(inputPath, outputPath, new Size(480, -1), TimeSpan.FromSeconds(10));• 合并视频片段
FFMpeg.Join(@"..\joined_video.mp4", @"..\part1.mp4", @"..\part2.mp4", @"..\part3.mp4");• 创建子视频
FFMpeg.SubVideo(inputPath, outputPath, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(30));• 将图片序列合并为视频
FFMpeg.JoinImageSequence(@"..\joined_video.mp4", frameRate: 1,
ImageInfo.FromPath(@"..\1.png"),
ImageInfo.FromPath(@"..\2.png"),
ImageInfo.FromPath(@"..\3.png"));• 静音视频文件
FFMpeg.Mute(inputPath, outputPath);• 提取音频轨道
FFMpeg.ExtractAudio(inputPath, outputPath);• 添加或替换音频轨道
FFMpeg.ReplaceAudio(inputPath, inputAudioPath, outputPath);• 将图片与音频文件结合
FFMpeg.PosterWithAudio(inputPath, inputAudioPath, outputPath);FFMpegCore 提供了一个强大的接口来在 .NET 中执行音视频处理任务,包括转码、裁剪、提取音频等操作。通过在项目中安装 FFMpegCore 库并配置 FFmpeg 可执行文件的路径,你可以轻松地在 C# 应用程序中实现各种音视频处理功能。