c# 通过ffmpeg操作视频

1.安装所需要的包

安装FFMpegCore
在这里插入图片描述

2. 下载ffmpeg和ffprobe

下载地址
在这里插入图片描述
将下载好的软件复制到项目中,然后设置为复制
在这里插入图片描述

要不然需要修改location的地址为存放ffmpeg的地址

3. 获取视频信息

using FFMpegCore;
using FFMpegCore.Enums;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Reflection;

namespace FfmpegStudy
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var loaction = Assembly.GetExecutingAssembly().Location;
            var folder = Directory.GetParent(loaction);
            //设置ffmpeg和ffprobe的路径
            GlobalFFOptions.Configure(new FFOptions { BinaryFolder = folder.FullName, TemporaryFilesFolder = folder.FullName });
            var videoPath = @"E:\360MoveData\Users\Administrator\Desktop\视频测试\test\aaa.mp4";
            // var videoOutPath = @"E:\360MoveData\Users\Administrator\Desktop\视频测试\test\aaa_1080.mp4";
            var videoFile = new FileInfo(videoPath);
            if (!videoFile.Exists)
            {
                Console.WriteLine("视频文件不存在");
                Console.ReadKey();
                return;
            }
            var mediaInfo = FFProbe.Analyse(videoPath);
            if (mediaInfo.VideoStreams.Count < 1)
            {
                Console.WriteLine("获取视频信息失败");
                Console.ReadKey();
            }
            Console.WriteLine(JsonConvert.SerializeObject(mediaInfo));
            Console.ReadKey();
        }
    }
}

结果

{
    "Duration":"00:01:37.0660000",
    "Format":{
        "Duration":"00:01:37.0660000",
        "StartTime":"00:00:00",
        "FormatName":"mov,mp4,m4a,3gp,3g2,mj2",
        "FormatLongName":"QuickTime / MOV",
        "StreamCount":2,
        "ProbeScore":100,
        "BitRate":37228816,
        "Tags":{
            "major_brand":"isom",
            "minor_version":"512",
            "compatible_brands":"isomiso2avc1mp41",
            "creation_time":"2023-02-15T03:41:56.000000Z",
            "Hw":"1",
            "bitrate":"45000000",
            "maxrate":"0",
            "te_is_reencode":"1",
            "encoder":"Lavf58.76.100"
        }
    },
    "PrimaryAudioStream":{
        "Channels":2,
        "ChannelLayout":"stereo",
        "SampleRateHz":44100,
        "Profile":"LC",
        "Index":1,
        "CodecName":"aac",
        "CodecLongName":"AAC (Advanced Audio Coding)",
        "CodecTagString":"mp4a",
        "CodecTag":"0x6134706d",
        "BitRate":191803,
        "StartTime":"00:00:00",
        "Duration":"00:01:37.0360000",
        "Language":"und",
        "Disposition":{
            "default":true,
            "dub":false,
            "original":false,
            "comment":false,
            "lyrics":false,
            "karaoke":false,
            "forced":false,
            "hearing_impaired":false,
            "visual_impaired":false,
            "clean_effects":false,
            "attached_pic":false,
            "timed_thumbnails":false,
            "captions":false,
            "descriptions":false,
            "metadata":false,
            "dependent":false,
            "still_image":false
        },
        "Tags":{
            "creation_time":"2023-02-15T03:41:56.000000Z",
            "language":"und",
            "handler_name":"SoundHandler",
            "vendor_id":"[0][0][0][0]"
        },
        "BitDepth":null
    },
    "PrimaryVideoStream":{
        "AvgFrameRate":30.000000206043957,
        "BitsPerRawSample":8,
        "DisplayAspectRatio":{
            "Item1":9,
            "Item2":16
        },
        "SampleAspectRatio":{
            "Item1":1,
            "Item2":1
        },
        "Profile":"High",
        "Width":2160,
        "Height":3840,
        "FrameRate":30,
        "PixelFormat":"yuv420p",
        "Rotation":0,
        "AverageFrameRate":0,
        "Index":0,
        "CodecName":"h264",
        "CodecLongName":"H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
        "CodecTagString":"avc1",
        "CodecTag":"0x31637661",
        "BitRate":37032413,
        "StartTime":"00:00:00",
        "Duration":"00:01:37.0660000",
        "Language":"und",
        "Disposition":{
            "default":true,
            "dub":false,
            "original":false,
            "comment":false,
            "lyrics":false,
            "karaoke":false,
            "forced":false,
            "hearing_impaired":false,
            "visual_impaired":false,
            "clean_effects":false,
            "attached_pic":false,
            "timed_thumbnails":false,
            "captions":false,
            "descriptions":false,
            "metadata":false,
            "dependent":false,
            "still_image":false
        },
        "Tags":{
            "creation_time":"2023-02-15T03:41:56.000000Z",
            "language":"und",
            "handler_name":"VideoHandler",
            "vendor_id":"[0][0][0][0]"
        },
        "BitDepth":8
    },
    "PrimarySubtitleStream":null,
    "VideoStreams":[
        {
            "AvgFrameRate":30.000000206043957,
            "BitsPerRawSample":8,
            "DisplayAspectRatio":{
                "Item1":9,
                "Item2":16
            },
            "SampleAspectRatio":{
                "Item1":1,
                "Item2":1
            },
            "Profile":"High",
            "Width":2160,
            "Height":3840,
            "FrameRate":30,
            "PixelFormat":"yuv420p",
            "Rotation":0,
            "AverageFrameRate":0,
            "Index":0,
            "CodecName":"h264",
            "CodecLongName":"H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
            "CodecTagString":"avc1",
            "CodecTag":"0x31637661",
            "BitRate":37032413,
            "StartTime":"00:00:00",
            "Duration":"00:01:37.0660000",
            "Language":"und",
            "Disposition":{
                "default":true,
                "dub":false,
                "original":false,
                "comment":false,
                "lyrics":false,
                "karaoke":false,
                "forced":false,
                "hearing_impaired":false,
                "visual_impaired":false,
                "clean_effects":false,
                "attached_pic":false,
                "timed_thumbnails":false,
                "captions":false,
                "descriptions":false,
                "metadata":false,
                "dependent":false,
                "still_image":false
            },
            "Tags":{
                "creation_time":"2023-02-15T03:41:56.000000Z",
                "language":"und",
                "handler_name":"VideoHandler",
                "vendor_id":"[0][0][0][0]"
            },
            "BitDepth":8
        }
    ],
    "AudioStreams":[
        {
            "Channels":2,
            "ChannelLayout":"stereo",
            "SampleRateHz":44100,
            "Profile":"LC",
            "Index":1,
            "CodecName":"aac",
            "CodecLongName":"AAC (Advanced Audio Coding)",
            "CodecTagString":"mp4a",
            "CodecTag":"0x6134706d",
            "BitRate":191803,
            "StartTime":"00:00:00",
            "Duration":"00:01:37.0360000",
            "Language":"und",
            "Disposition":{
                "default":true,
                "dub":false,
                "original":false,
                "comment":false,
                "lyrics":false,
                "karaoke":false,
                "forced":false,
                "hearing_impaired":false,
                "visual_impaired":false,
                "clean_effects":false,
                "attached_pic":false,
                "timed_thumbnails":false,
                "captions":false,
                "descriptions":false,
                "metadata":false,
                "dependent":false,
                "still_image":false
            },
            "Tags":{
                "creation_time":"2023-02-15T03:41:56.000000Z",
                "language":"und",
                "handler_name":"SoundHandler",
                "vendor_id":"[0][0][0][0]"
            },
            "BitDepth":null
        }
    ],
    "SubtitleStreams":[

    ],
    "ErrorData":[

    ]
}

宽度高度和时长

 var videoInfomation = mediaInfo.VideoStreams[0];
 var videoWidth = videoInfomation.Width;
 var videoHeight = videoInfomation.Height;
 var dur = (int)videoInfomation.Duration.TotalSeconds
 Console.WriteLine($"原始视频宽度:{videoWidth}\t高度:{videoHeight}");

4. 压缩视频

using FFMpegCore;
using FFMpegCore.Enums;
using System;
using System.IO;
using System.Reflection;

namespace FfmpegStudy
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var loaction = Assembly.GetExecutingAssembly().Location;
            var folder = Directory.GetParent(loaction);
            GlobalFFOptions.Configure(new FFOptions { BinaryFolder = folder.FullName, TemporaryFilesFolder = folder.FullName });
            var videoPath = @"E:\360MoveData\Users\Administrator\Desktop\视频测试\test\aaa.mp4";
            // var videoOutPath = @"E:\360MoveData\Users\Administrator\Desktop\视频测试\test\aaa_1080.mp4";
            var videoFile = new FileInfo(videoPath);
            if (!videoFile.Exists)
            {
                Console.WriteLine("视频文件不存在");
                Console.ReadKey();
                return;
            }
            var mediaInfo = FFProbe.Analyse(videoPath);
            if (mediaInfo.VideoStreams.Count < 1)
            {
                Console.WriteLine("获取视频信息失败");
                Console.ReadKey();
            }
            var videoInfomation = mediaInfo.VideoStreams[0];
            var videoWidth = videoInfomation.Width;
            var videoHeight = videoInfomation.Height;
            Console.WriteLine($"原始视频宽度:{videoWidth}\t高度:{videoHeight}");
            //判断宽度为1080还是高度为1080
            if (videoWidth > 1080 || videoHeight > 1080)
            {
                if (videoWidth >= videoHeight)
                {
                    videoWidth = 1080;
                    videoHeight = (int)((1080.0 / videoWidth) * videoHeight);
                    if (videoHeight % 2 != 0)
                    {
                        videoHeight += 1;
                    }
                }
                else
                {
                    videoWidth = (int)((1080.0 / videoHeight) * videoWidth);
                    if (videoWidth % 2 != 0)
                    {
                        videoWidth += 1;
                    }
                    videoHeight = 1080;
                }
            }
            Console.WriteLine($"压缩后视频宽度:{videoWidth}\t高度:{videoHeight}");
            var ffmpegArgs = FFMpegArguments.FromFileInput(videoPath)
                .OutputToFile(videoPath, true,
                options => options.WithVideoCodec(VideoCodec.LibX264)
                .WithConstantRateFactor(28)
                .WithAudioCodec(AudioCodec.Aac)
                //.WithVariableBitrate(4)
                .WithFramerate(20)
                .WithVideoFilters(filterOptions => filterOptions
                .Scale(videoWidth, videoHeight))//width和height不允许为单数
                .WithFastStart());
            //Console.WriteLine(ffmpegArgs.Arguments);//打印ffmpeg运行命令
            ffmpegArgs.ProcessSynchronously();
            Console.WriteLine("处理完毕...");
            Console.ReadKey();
        }
    }
}

原视频380M,压缩后4.7M
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

假装我不帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值