FFMpegCore:.NET 中进行音视频处理解决方案

发布于:2025-02-26 ⋅ 阅读:(23) ⋅ 点赞:(0)

简介

FFMpegCore 是一个基于 .NET Standard 的 FFMpeg/FFProbe 封装库,用于轻松将媒体分析和转换功能集成到应用程序中。它支持同步和异步调用。

安装和配置

1. 安装库

Install-Package FFMpegCore

FFMpegCore 库本身不包含 FFmpeg 可执行文件,因此需要手动下载并指定其路径。可以从 FFmpeg 官方网站 下载适合操作系统的版本。

2. 配置 FFmpeg 路径

全局配置
GlobalFFOptions.Configure(new FFOptions 
{ 
    BinaryFolder = "./ffmpeg", 
    TemporaryFilesFolder = "/tmp" 
});
单次运行配置
await FFMpegArguments
    .FromFileInput(inputPath)
    .OutputToFile(outputPath)
    .ProcessAsynchronously(true, new FFOptions 
    { 
        BinaryFolder = "./bin", 
        TemporaryFilesFolder = "/tmp" 
    });
通过项目文件配置

.csproj 文件中添加以下内容:

<ItemGroup>
    <Resource Include="ffmpeg\ffmpeg.exe" />
    <Resource Include="ffmpeg\ffplay.exe" />
    <Resource Include="ffmpeg\ffprobe.exe" />
</ItemGroup>
通过配置文件配置

创建 ffmpeg.config.json 文件:

{
    "BinaryFolder": "./bin",
    "TemporaryFilesFolder": "/tmp"
}

API 使用

1. 使用 FFProbe 分析媒体文件

var mediaInfo = await FFProbe.AnalyseAsync(inputPath);
// 或同步方式
var mediaInfo = FFProbe.Analyse(inputPath);

2. 使用 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();

3. 从流中转换或输出到流

await FFMpegArguments
    .FromPipeInput(new StreamPipeSource(inputStream))
    .OutputToPipe(new StreamPipeSink(outputStream), options => options
        .WithVideoCodec("vp9")
        .ForceFormat("webm"))
    .ProcessAsynchronously();

4. 辅助方法

捕获快照
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# 应用程序中轻松实现各种音视频处理功能。