Xamarin -视频裁剪iOS
本文关键字:iOS 裁剪 视频 Xamarin | 更新日期: 2023-09-27 18:13:19
我想知道是否有一种在Xamarin中裁剪视频的方法。我似乎找不到任何例子。我试着看看现有的函数和类,但我找不到任何东西。
基本上是制作像Vine和Instagram那样的方形视频。我想这是通过裁剪视频的其余部分来完成的,而不仅仅是放大。
我从一个来源找到部分代码,我试图添加所有者,但我找不到。解决方案的关键部分是由我添加的裁剪,这是AVVideoSettingsCompressed中的"VideoCleanAperture"。
videoUrl = ((AVFoundation.AVUrlAsset)avAsset).Url;
NSError assetReaderError;
var assetReader = AVAssetReader.FromAsset(avAsset, out assetReaderError);
var assetTrack = avAsset.Tracks.First();
//Height = (System.nint?)avAsset.NaturalSize.Height,
//Width = (System.nint?)avAsset.NaturalSize.Width,
var inputSettings = new AVVideoSettingsUncompressed()
{
Height = (System.nint?)avAsset.NaturalSize.Height,
Width = (System.nint?)avAsset.NaturalSize.Width,
};
var assetReaderOutput = new AVAssetReaderTrackOutput(assetTrack, settings: inputSettings);
assetReaderOutput.AlwaysCopiesSampleData = false;
string tempFile = Path.Combine(Path.GetTempPath(), "CroppedVideo.mp4");
if (File.Exists(tempFile)) File.Delete(tempFile);
var url = NSUrl.FromFilename(tempFile);
NSError assetWriterError;
var assetWriter = new AVAssetWriter(url, AVFileType.Mpeg4, out assetWriterError);
var outputSettings = new AVVideoSettingsCompressed()
{
Height = 300,
Width = 300,
Codec = AVVideoCodec.H264,
CodecSettings = new AVVideoCodecSettings()
{
AverageBitRate = 1000000,
VideoCleanAperture = new AVVideoCleanApertureSettings(
new NSDictionary(
AVVideo.CleanApertureWidthKey, new NSNumber(300),
AVVideo.CleanApertureHeightKey, new NSNumber(300),
AVVideo.CleanApertureVerticalOffsetKey, new NSNumber(10),
AVVideo.CleanApertureHorizontalOffsetKey, new NSNumber(10)
)
)
},
ScalingMode = AVVideoScalingMode.ResizeAspectFill
};
var assetWriterInput = new AVAssetWriterInput(mediaType: AVMediaType.Video, outputSettings: outputSettings);
assetWriterInput.ExpectsMediaDataInRealTime = false;
assetWriter.AddInput(assetWriterInput);
assetWriter.StartWriting();
assetReader.AddOutput(assetReaderOutput);
assetReader.StartReading();
assetWriter.StartSessionAtSourceTime(CoreMedia.CMTime.Zero);
var mediaInputQueue = new DispatchQueue("mediaInputQueue");
assetWriterInput.RequestMediaData(mediaInputQueue, () =>
{
while (assetWriterInput.ReadyForMoreMediaData)
{
var nextBuffer = assetReaderOutput.CopyNextSampleBuffer();
if (nextBuffer != null)
{
assetWriterInput.AppendSampleBuffer(nextBuffer);
}
else
{
assetWriterInput.MarkAsFinished();
assetWriter.FinishWritingAsync();
assetReader.CancelReading();
assetReader.Dispose();
assetReaderOutput.Dispose();
assetWriter.Dispose();
assetWriterInput.Dispose();
break;
}
}
});
}