我想知道是否有办法在Xamarin中裁剪视频。我似乎无法找到任何例子。我试着查看现有的函数和类,但我找不到任何东西。
基本上制作像Vine和Instagram一样的方形视频。我认为这是通过裁剪视频的其余部分而不仅仅是放大来完成的。
答案 0 :(得分:0)
我从一个来源找到部分代码,我试图添加所有者,但我找不到。该解决方案的关键部分由我添加用于裁剪,即" VideoCleanAperture"在AVVideoSettingsCompressed中。
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;
}
}
});
}