Files
downkyicore/DownKyi.Core/FFmpeg/FFmpegHelper.cs
2023-11-25 21:59:48 +08:00

116 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using DownKyi.Core.Logging;
using FFMpegCore;
using FFMpegCore.Enums;
namespace DownKyi.Core.FFmpeg;
public static class FFmpegHelper
{
private const string Tag = "FFmpegHelper";
/// <summary>
/// 合并音频和视频
/// </summary>
/// <param name="audio">音频</param>
/// <param name="video">视频</param>
/// <param name="destVideo"></param>
public static bool MergeVideo(string audio, string video, string destVideo)
{
if (!File.Exists(audio) && !File.Exists(video)) return false;
FFMpegArguments
.FromFileInput(audio)
.AddFileInput(video)
.OutputToFile(destVideo, true, options => options
.WithAudioCodec("copy")
.WithVideoCodec("copy")
.ForceFormat("mp4"))
.ProcessSynchronously();
try
{
if (audio != null)
{
File.Delete(audio);
}
if (video != null)
{
File.Delete(video);
}
}
catch (IOException e)
{
Console.WriteLine("MergeVideo()发生IO异常: {0}", e);
LogManager.Error(Tag, e);
}
return true;
}
/// <summary>
/// 去水印非常消耗cpu资源
/// </summary>
/// <param name="video"></param>
/// <param name="destVideo"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="action"></param>
public static void Delogo(string video, string destVideo, int x, int y, int width, int height,
Action<string> action)
{
var arg = FFMpegArguments
.FromFileInput(video)
.OutputToFile(
destVideo,
true,
option => option
.WithCustomArgument($"-vf delogo=x={x}:y={y}:w={width}:h={height}:show=0 -hide_banner"))
.NotifyOnOutput(action.Invoke)
.NotifyOnError(action.Invoke)
.ProcessSynchronously();
}
/// <summary>
/// 从一个视频中仅提取音频
/// </summary>
/// <param name="video">源视频</param>
/// <param name="audio">目标音频</param>
/// <param name="action">输出信息</param>
public static void ExtractAudio(string video, string audio, Action<string> action)
{
FFMpegArguments
.FromFileInput(video)
.OutputToFile(audio,
true,
options => options
.WithCustomArgument("-hide_banner")
.WithAudioCodec("copy")
.DisableChannel(Channel.Video)
)
.NotifyOnOutput(action.Invoke)
.NotifyOnError(action.Invoke)
.ProcessSynchronously();
}
/// <summary>
/// 从一个视频中仅提取视频
/// </summary>
/// <param name="video">源视频</param>
/// <param name="destVideo">目标视频</param>
/// <param name="action">输出信息</param>
public static void ExtractVideo(string video, string destVideo, Action<string> action)
{
FFMpegArguments.FromFileInput(video)
.OutputToFile(
destVideo,
true,
options => options
.WithCustomArgument("-hide_banner")
.WithVideoCodec("copy")
.DisableChannel(Channel.Audio))
.NotifyOnOutput(action.Invoke)
.NotifyOnError(action.Invoke)
.ProcessSynchronously();
}
}