Unity使用FFMpeg

Unity启动FFMpeg

private static bool StartUpFFmpeg()
        {
            bool isWinPlatform = true;
            if (Application.platform != RuntimePlatform.WindowsEditor &&
                Application.platform != RuntimePlatform.WindowsPlayer)
            {
                isWinPlatform = false;
            }

            if (!isWinPlatform)
            {
                string iOSPath = string.Empty;
                string extcutablesPath = string.Empty;
                if (Application.platform == RuntimePlatform.OSXEditor)
                {
                    iOSPath = Path.Combine(Application.dataPath, "CKTools/Plugins/FFMpeg/Mac/ffmpeg");
                    extcutablesPath = Path.Combine(Application.dataPath, "CKTools/Plugins/FFMpeg/Mac");
                }
                else if (Application.platform == RuntimePlatform.OSXPlayer)
                {
                    iOSPath = Util.BuildsPath.Replace("YRBuilds", "FFMpeg/ffmpeg");
                    extcutablesPath = Util.BuildsPath.Replace("YRBuilds", "FFMpeg");
                }

                sys_chmod(iOSPath, 755);
                FFmpeg.SetExecutablesPath(extcutablesPath, "ffmpeg", "ffmpeg");
            }
            else
            {
                string extcutablesPath = string.Empty;
                if (Application.platform == RuntimePlatform.WindowsEditor)
                    extcutablesPath = Path.Combine(Application.dataPath, "CKTools/Plugins/FFMpeg/Windows");
                else if (Application.platform == RuntimePlatform.WindowsPlayer)
                    extcutablesPath = Util.BuildsPath.Replace("YRBuilds", "FFMpeg");

                FFmpeg.SetExecutablesPath(extcutablesPath, "ffmpeg", "ffmpeg");
            }
            return true;
        }
使用ffmpeg将音频文件转为wav 16k 单声道
   public static async UniTask ConvertToWav(string inputFile, string outputPath = null)
        {
            if (string.IsNullOrEmpty(outputPath))
            {
                outputPath = Path.Combine(Path.GetDirectoryName(inputFile),
                    Path.GetFileNameWithoutExtension(inputFile) + "_bak.wav");
            }

            if (File.Exists(outputPath)) File.Delete(outputPath);

            if (!StartUpFFmpeg())
                return;
            string arguments = $"-i {inputFile} -vn -ar 16000 -ac 1 -b:a 16k -f wav -y {outputPath}";
            await FFmpeg.Conversions.New().Start(arguments);
        }

 对于图片的水平或者竖向分割

  public static async void SplitHalfOfPicture(string inputPath, string outPath1 = null, string outPath2 = null,
            string spliteType = "Ver")
        {
            if (!StartUpFFmpeg() || string.IsNullOrEmpty(inputPath))
                return;
            if (!File.Exists(inputPath))
            {
                YRLog.LogInfo("CKUtils SplitHalfOfPicture", $"文件不存在。路径:{inputPath}");
                return;
            }

            string extension = Path.GetExtension(inputPath);
            if (string.IsNullOrEmpty(outPath1))
                outPath1 = inputPath.Replace($".{extension}", $"split_1.{extension}");
            if (string.IsNullOrEmpty(outPath2))
                outPath2 = inputPath.Replace($".{extension}", $"split_2.{extension}");
            string arguments;
            if (spliteType.Equals("Ver"))
                arguments =
                    $" -i \"{inputPath}\" -vf 'crop=iw/2:ih:0:0' -lossless 0 -quality 75 -y \"{outPath1}\" -vf 'crop=iw/2:ih:iw/2:0' -lossless 0 -quality 75 -y \"{outPath2}\"";
            else
                arguments =
                    $" -i \"{inputPath}\" -vf 'crop=iw:ih/2:0:0' -lossless 0 -quality 75 -y \"{outPath1}\" -vf 'crop=iw:ih/2:0:ih/2' -lossless 0 -quality 75 -y \"{outPath2}\"";
            await FFmpeg.Conversions.New().Start(arguments);
        }
图片大于1920*1080 = 2073600 进行压缩
   public static async UniTask ScalePicture(string inputPath, Action action = null)
        {
            if (!StartUpFFmpeg())
                return;
            string suffix = Path.GetExtension(inputPath);

            string outPath = inputPath;
            if (!suffix.Equals(".jpg"))
            {
                outPath = inputPath.Replace(suffix, ".jpg");
                if (File.Exists(outPath))
                    File.Delete(outPath);
                File.Move(inputPath, outPath);
            }

            string tmpOutputPath = Path.Combine(Path.GetDirectoryName(outPath),
                Path.GetFileNameWithoutExtension(outPath) + "_bak.jpg");

            //-pix_fmt yuva422p  某些图片会如果色彩空间是 YUVA 通过命令会 YUV 色彩饱和度会增加 
            string arguments1 =
                $"-i \"{outPath}\" -vf \"scale='if(gt(ih*iw,2073600),iw/sqrt(ih*iw/2073600),iw)':'if(gt(ih*iw,2073600),ih/sqrt(ih*iw/2073600),ih)'\"  -y \"{tmpOutputPath}\" ";
            Debug.Log("ScalePicture ffmpeg:" + arguments1);

            await FFmpeg.Conversions.New().Start(arguments1);
            if (File.Exists(outPath))
            {
                try
                {
                    File.Create(outPath).Dispose();
                    File.Delete(outPath);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }

            if (File.Exists(tmpOutputPath))
            {
                if (File.Exists(inputPath))
                {
                    try
                    {
                        File.Create(inputPath).Dispose();
                        File.Delete(inputPath);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                }

                File.Move(tmpOutputPath, inputPath);
            }

            action?.Invoke();
        }

压缩视频

  public static async UniTask CompressVideo(string inputPath)
        {
            if (!StartUpFFmpeg())
                return;
            if (!File.Exists(inputPath))
                return;
            string rawPath = inputPath.Replace(".mp4", "_raw.mp4");
            if (File.Exists(rawPath))
                File.Delete(rawPath);
            File.Move(inputPath, rawPath);
            // string arguments = $"-i \"{rawPath}\" -s 1920*1080 -b:v 2000k -y \"{inputPath}\"";
            string arguments =
                $"-i \"{rawPath}\" -vf scale=-1:1080 -b:v {CKStatics.VIDEO_LIMIT_BITRATE}k -r 25 -c:v libx264 -profile:v main -level:v 4.0 -c:a copy -y \"{inputPath}\"";
            Debug.Log("CompressVideo ffmpeg:" + arguments);
            await FFmpeg.Conversions.New().Start(arguments);
        }
根据时间点 切割音频
 public static async UniTask SplitAudioByTime(string audioPath, List<float> times)
        {
            if (!StartUpFFmpeg())
                return;
            if (times == null || times.Count <= 0)
                return;
            //需要对时间排序 如果顺序不对 FFmpeg会报错
            times.Sort((a, b) => (a.CompareTo(b)));
            string tempTimes = string.Empty;
            for (int i = 0; i < times.Count; i++)
            {
                string time = SecondToHour(times[i]);
                if (i == times.Count - 1)
                    tempTimes = $"{tempTimes}{time}";
                else
                    tempTimes = $"{tempTimes}{time},";
            }

            YRLog.LogInfo(TAG, "根据时间点 切割音频");
            string extension = Path.GetExtension(audioPath);
            string noExtensionPath = Path.GetFullPath(audioPath).Replace(extension, "");
            string arguments =
                $"-i \"{audioPath}\" -f segment -segment_times {tempTimes} -c copy -map 0 \"{noExtensionPath}_%d{extension}\"";
            YRLog.LogInfo(TAG, $"SplitAudioByTime arguments:{arguments}");
            await FFmpeg.Conversions.New().Start(arguments);
        }

压缩音频成为MP3

  public static async UniTask<string> CompressAudioToMp3(string inputPath)
        {
            if (!StartUpFFmpeg())
                return inputPath;
            string dir = Path.GetDirectoryName(inputPath).Replace("\\", "/");
            string name = Path.GetFileNameWithoutExtension(inputPath);
            string outPath = $"{dir}/_fix{name}.mp3";
            string tempInputPath = string.Empty;
            string tempOutPath = string.Empty;
            if (CKStatics.toolModeType != ToolModeType.Course)
            {
                tempInputPath = CKBookUtils.GetBookAbsolutePath(inputPath);
                tempOutPath = CKBookUtils.GetBookAbsolutePath(outPath);
                if (!File.Exists(tempInputPath))
                {
                    CKToast.Instance.ToastShow("文件不存在");
                    YRLog.LogInfo(TAG, $"{tempInputPath} 文件不存在");
                    return inputPath;
                }
            }
            else
            {
                tempInputPath = inputPath;
                tempOutPath = outPath;
            }

            string arguments = $"-i {tempInputPath} -vn -ar 44100 -ac 2 -b:a 192k -acodec mp3 -y {tempOutPath}";
            YRLog.LogInfo(TAG, $"CompressAudioToMp3 参数 {arguments}");
            await FFmpeg.Conversions.New().Start(arguments);
            return outPath;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值