我使用AVCaptureSession
從設備攝像頭捕獲視頻,然後使用AVAssetWriterInput
和AVAssetTrack
在將視頻上傳到服務器之前對其進行壓縮/調整大小。最終的視頻將通過html5視頻元素在網絡上進行查看。AVFoundation - 爲什麼我無法獲得視頻方向
我遇到了多個問題,試圖讓視頻的方向正確。我的應用程序僅支持橫向導航,所有捕捉的視頻都應處於橫向模式。但是,我希望允許用戶在任何橫向(即左側或右側的主頁按鈕)上握住設備。
我能夠使視頻預覽顯示在正確的方向與下面的代碼行
_previewLayer.connection.videoOrientation = UIDevice.currentDevice.orientation;
的問題,通過AVAssetWriterInput
和朋友在處理視頻時啓動。結果似乎沒有考慮到視頻被捕獲到的左側和右側風景模式。IOW,有時視頻出現顛倒。一些谷歌搜索後,我發現很多人建議,下面的代碼行將解決這個問題
writerInput.transform = videoTrack.preferredTransform;
......但這似乎並不奏效。有點調試後,我發現,videoTrack.preferredTransform
始終是相同的值,而不管取向的視頻在。
捕捉我試圖手動跟蹤什麼方位的視頻在捕獲,並根據需要設置writerInput.transform
到CGAffineTransformMakeRotation(M_PI)
。哪個解決了問題!!!
... sorta
當我在設備上查看結果時,該解決方案按預期工作。無論記錄時的左右方向如何,視頻都是正面朝上的。不幸的是,當我在另一個瀏覽器中查看完全相同的視頻(Mac書上的chrome)時,它們都是顛倒的!?!?!?
我在做什麼錯?
編輯
下面是一些代碼,如果它是有幫助...
-(void)compressFile:(NSURL*)inUrl;
{
NSString* fileName = [@"compressed." stringByAppendingString:inUrl.lastPathComponent];
NSError* error;
NSURL* outUrl = [PlatformHelper getFilePath:fileName error:&error];
NSDictionary* compressionSettings = @{ AVVideoProfileLevelKey: AVVideoProfileLevelH264Main31,
AVVideoAverageBitRateKey: [NSNumber numberWithInt:2500000],
AVVideoMaxKeyFrameIntervalKey: [NSNumber numberWithInt: 30] };
NSDictionary* videoSettings = @{ AVVideoCodecKey: AVVideoCodecH264,
AVVideoWidthKey: [NSNumber numberWithInt:1280],
AVVideoHeightKey: [NSNumber numberWithInt:720],
AVVideoScalingModeKey: AVVideoScalingModeResizeAspectFill,
AVVideoCompressionPropertiesKey: compressionSettings };
NSDictionary* videoOptions = @{ (id)kCVPixelBufferPixelFormatTypeKey: [NSNumber numberWithInt:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange] };
AVAssetWriterInput* writerInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
writerInput.expectsMediaDataInRealTime = YES;
AVAssetWriter* assetWriter = [AVAssetWriter assetWriterWithURL:outUrl fileType:AVFileTypeMPEG4 error:&error];
assetWriter.shouldOptimizeForNetworkUse = YES;
[assetWriter addInput:writerInput];
AVURLAsset* asset = [AVURLAsset URLAssetWithURL:inUrl options:nil];
AVAssetTrack* videoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
// !!! this line does not work as expected and causes all sorts of issues (videos display sideways in some cases) !!!
//writerInput.transform = videoTrack.preferredTransform;
AVAssetReaderTrackOutput* readerOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:videoTrack outputSettings:videoOptions];
AVAssetReader* assetReader = [AVAssetReader assetReaderWithAsset:asset error:&error];
[assetReader addOutput:readerOutput];
[assetWriter startWriting];
[assetWriter startSessionAtSourceTime:kCMTimeZero];
[assetReader startReading];
[writerInput requestMediaDataWhenReadyOnQueue:_processingQueue usingBlock:
^{
/* snip */
}];
}
太謝謝你了。 – herbrandson