基本信息
源码名称:C#视频操作学习Tips(5) 音频、视频选择多段删除
源码大小:80.07M
文件格式:.rar
开发语言:C#
更新时间:2025-12-02
   源码介绍
Visual Studio 2022, WPF .NET 8.0。调用FFmpeg函数与WinForm通用,可直接用于WinForm。
为便于说明,均采用后台代码。

由于管道操作,不生成临时文件,所以在删除多段视频后重新编码该视频,比较耗时。

删除音频,直接将需要设置的多段视频设置为静音。

选好多段后,点击“保存编辑”,另存视频。

 public class Project
 {
     public string Id = "";
     public EditType Etype;
     public double Begin_Time;
     public double End_Time;
     public int Rate;
     public double Clong;
 }
 public static List<Project> Projects = [];
 
 public async static void Delete_Video(string file)
{
    int pcount = Projects.Count;
    var proj = Projects.Where(d=>d.Etype==EditType.DeleteVideo).OrderBy(n=>n.Begin_Time).ToList();
    string arguments = "\"";

    int n = 0;
    if (proj[0].Begin_Time != 0)
    {
        arguments  = $"[0:v]trim=0:{proj[0].Begin_Time},setpts=PTS-STARTPTS[v0]; [0:a]atrim=0:{proj[0].Begin_Time},asetpts=PTS-STARTPTS[a0]; ";
        n  ;
    }

    for (int i = 0; i < pcount; i  )
    {
        if (i== pcount-1)
        {
            arguments  = $"[0:v]trim={proj[i].End_Time},setpts=PTS-STARTPTS[v{n}]; [0:a]atrim={proj[i].End_Time},asetpts=PTS-STARTPTS[a{n}]; "; 
        }
        else
        {
            arguments  = $"[0:v]trim={proj[i].End_Time}:{proj[i   1].Begin_Time},setpts=PTS-STARTPTS[v{n}]; [0:a]atrim={proj[i].End_Time}:{proj[i   1].Begin_Time},asetpts=PTS-STARTPTS[a{n}]; ";
        }
        n  ;
    }

    string sb = "";
    for (int i = 0; i < n; i  )
    {
        sb  = $"[v{i}][a{i}]";
    }
    sb  = $"concat=n={n}:v=1:a=1[outv][outa]\" -map \"[outv]\" -map \"[outa]\" ";

    arguments  = sb $"-c:v libx264 -preset veryslow -crf 18 -c:a aac -b:a 192k -movflags  faststart -y output.mp4";
    arguments = $"-i \"{file}\" -filter_complex "   arguments;
    
    var psi = new ProcessStartInfo
    {
        FileName = FFmpegPath,
        Arguments = arguments,
        UseShellExecute = false,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        CreateNoWindow = true
    };
    
    var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
    process.Start();

    while (!process.StandardError.EndOfStream)
    {
        var line = await process.StandardError.ReadLineAsync();
        if (line != null && line.Contains("time="))
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                //pw.File_Block.Text = line; // 进度
            });
        }
    }

    await process.WaitForExitAsync();
    Application.Current.Dispatcher.Invoke(() =>
    {
        pw.Close();
        SaveFileDialog sfd = new()
        {
            Filter = "视频文件(*.mp4)|*.mp4",
            FilterIndex = 1,
            RestoreDirectory = true,
            FileName = System.IO.Path.GetFileName("视频.mp4")
        };
        if (sfd.ShowDialog() == true)
        {
            File.Copy(Directory.GetCurrentDirectory()   @"\output.mp4", sfd.FileName, true);
        }
    });
}