How to compress(Zip) a video in xamarin forms

坚强是说给别人听的谎言 提交于 2021-02-08 12:14:27

问题


I want to compress a large sized video and upload it into the server.How can I do this, I have no idea about this.

Please help me....


回答1:


Firstly - Zipping of video content is unlikely to reduce its size in any meaningful way. What you should be looking at is different codecs and encoding mechanisms for reducing its size.

Look at ffmpeg : ffmpeg dot org

You can call this tool on the command line via the System.Diagnostics.Process class. You can then tell it to process a video file. This will allow you to change the encoding and codecs used by a video. Note - reducing the size can reduce the quality of a video. You may also want to down scale the resolution of the video to get the largest reduction in size.

Video and Audio are types of media that cannot be compressed with conventional tools such as winzip or winrar and end up smaller files. Typically you will end up only reducing their file size by 1%. To reduce their file size, you need to alter the video encoding, which can in some cases reduce the quality.

ffmpeg -i myVideo.avi -fs 20M myOutputVideo.avi

This command line will take myVideo.avi which could be 100 mb or larger, and try to downgrade the quality / encoding bitrate to get 20mb output size.

public static void ShrinkVideo(string pathToVideo,int desiredMbSize,string outFile)
{
     ProcessStartInfo psi = new ProcessStartInfo("ffmpeg.exe");
     psi.Arguments = string.Format("-i \"{0}\" -fs {1}M \"{2}\"",pathToVideo,desiredMbSize,outFile);
     Process proc = new Process(psi);
     proc.Start();
}

I havent tested this code - but it should do something along the lines of what you want. If you get errors - post back.

BTW- This has a dependency on ffmpeg.exe - which is a third party executable. It is commonly and widely used - it is regarded as one of the most compatible and versatile video encoders - very well supported by the community.




回答2:


Use Following code in DS file for Android

public Task CompressVideo(string path) {

        var task = new TaskCompletionSource<string>();

        var _workingDirectory = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
        var sourceMp4 = path;
        var destinationPath1 = IntentHelper.CreateNewVideoPath();
        FFMpeg ffmpeg = new FFMpeg(Android.App.Application.Context, _workingDirectory);
        TransposeVideoFilter vfTranspose = new TransposeVideoFilter(TransposeVideoFilter.NINETY_CLOCKWISE);
        var filters = new List<VideoFilter>();
        filters.Add(vfTranspose);

        Task.Run(() =>
        {
            var sourceClip = new Clip(System.IO.Path.Combine(_workingDirectory, sourceMp4)) { videoFilter = VideoFilter.Build(filters) };
            var onComplete = new MyCommand((_) =>
            {
                CurrentActivity.RunOnUiThread(() =>
                {
                    task.SetResult(destinationPath1);
                    //progress.Dismiss();
                });
            });

            var onMessage = new MyCommand((message) =>
            {
                System.Console.WriteLine(message);
            });

            var callbacks = new FFMpegCallbacks(onComplete, onMessage);
            string[] cmds = new string[] {
                    "-y",
                    "-i",
                    sourceClip.path,
                    "-strict", "experimental",
                    "-vcodec", "libx264",
                    "-preset", "ultrafast",
                    "-crf","38", "-acodec","aac", "-ar", "44100" ,
                    "-q:v", "12",
                      "-vf",sourceClip.videoFilter,
                    destinationPath1 ,
                      };
            ffmpeg.Execute(cmds, callbacks);
            return task.Task;
        });
        return task.Task;
    }

    public class MyCommand : ICommand
    {
        public delegate void ICommandOnExecute(object parameter = null);
        public delegate bool ICommandOnCanExecute(object parameter);

        private ICommandOnExecute _execute;
        private ICommandOnCanExecute _canExecute;

        public MyCommand(ICommandOnExecute onExecuteMethod)
        {
            _execute = onExecuteMethod;
        }

        public MyCommand(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod)
        {
            _execute = onExecuteMethod;
            _canExecute = onCanExecuteMethod;
        }

        #region ICommand Members

        public event EventHandler CanExecuteChanged
        {
            add { throw new NotImplementedException(); }
            remove { throw new NotImplementedException(); }
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null && _execute != null)
                return true;

            return _canExecute.Invoke(parameter);
        }

        public void Execute(object parameter)
        {
            if (_execute == null)
                return;

            _execute.Invoke(parameter);
        }

        #endregion
    }

Now use this code in Dependency File for iOS

public Task CompressVideo(string inputPath) {

        var task = new TaskCompletionSource<string>();
        var export = new AVAssetExportSession(AVAsset.FromUrl(new NSUrl(inputPath)), AVAssetExportSession.PresetMediumQuality);
        string videoFilename = System.IO.Path.Combine(GetVideoDirectoryPath(), GetUniqueFileName(".mp4"));
        export.OutputUrl = NSUrl.FromFilename(videoFilename);
        export.OutputFileType = AVFileType.Mpeg4;
        export.ShouldOptimizeForNetworkUse = true;
        export.ExportAsynchronously(() =>
        {
            if (export.Status == AVAssetExportSessionStatus.Completed)
            {
                var videoData = NSData.FromUrl(NSUrl.FromString(export.OutputUrl.ToString()));
                NSError err = null;
                if (videoData.Save(videoFilename, false, out err))
                    task.SetResult(videoFilename);
                else
                    task.SetResult(null);
            }
            else
                task.SetResult(null);
        });

        return task.Task;


来源:https://stackoverflow.com/questions/49940463/how-to-compresszip-a-video-in-xamarin-forms

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!