我想在Xamarin(iOS)中“压缩”视频(上传)。 我发现了AVAssetWriter类和红色,您可以设置分辨率,比特率等。 你会怎么用?还有哪些课? 正如您可能已经注意到的,我对应用程序开发非常新。
答案 0 :(得分:2)
以下是使用AVAssetReader将AVAssetWriter提供给重新采样和/或转码视频的示例。
在这个例子中,我正在拍摄一个名为“Pool.mp4”的视频,该视频包含在应用程序包(BundleResource)中并以“NewVideo.mp4”的形式保存到“tmp”目录中,大小为300x300,1Mbps(减少)原始文件大小〜50%......)
注意:没有检查返回值或错误代码,这是由执行者决定的。
var asset = AVAsset.FromUrl(NSUrl.FromFilename("Pool.mp4"));
NSError assetReaderError;
var assetReader = AVAssetReader.FromAsset(asset, out assetReaderError);
var assetTrack = asset.Tracks.First();
var inputSettings = new AVVideoSettingsUncompressed()
{
Height = 300,
Width = 300,
};
var assetReaderOutput = new AVAssetReaderTrackOutput(assetTrack, settings: inputSettings);
assetReaderOutput.AlwaysCopiesSampleData = false;
string tempFile = Path.Combine(Path.GetTempPath(), "NewVideo.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
}
};
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;
}
}
});