[英]AVAssetExportSession - exported video not compatible with camera roll
[英]Video not always exported to Camera Roll: NSFileManager's removeItemAtPath non-blocking?
閱讀幾個教程后,像這樣的,看着其他代碼導出視頻,我們仍然無法解決問題。
有時新視頻會導出到相機膠卷,有時則不會。 我們甚至無法始終如一地重現該問題。
我們可以想象的唯一問題是NSFileManager.defaultManager().removeItemAtPath
是否不是阻塞調用,但沒有文檔表明它是異步的,所以我們假設情況並非如此。
每次, writeVideoAtPathToSavedPhotosAlbum
閉包中的“已保存視頻” println
都會被調用,表明視頻已成功寫入相機膠卷,但我們在那里看不到視頻。
關於如何排除故障的建議?
代碼:
// -- Get path
let fileName = "/editedVideo.mp4"
let allPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docsPath = allPaths[0] as! NSString
let exportPath = docsPath.stringByAppendingFormat(fileName)
let exportUrl = NSURL.fileURLWithPath(exportPath as String)!
println(exportPath)
// -- Remove old video?
if NSFileManager.defaultManager().fileExistsAtPath(exportPath as String) {
println("Deleting existing file\n")
NSFileManager.defaultManager().removeItemAtPath(exportPath as String, error: nil)
}
// -- Create exporter
let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)
exporter.videoComposition = mutableComposition
exporter.outputFileType = AVFileTypeMPEG4
exporter.outputURL = exportUrl
exporter.shouldOptimizeForNetworkUse = true
// -- Export video
exporter.exportAsynchronouslyWithCompletionHandler({
self.exportDidFinish(exporter)
})
}
func exportDidFinish(exporter: AVAssetExportSession) {
println("Finished exporting video!")
// Write out video to photo album
let assetLibrary = ALAssetsLibrary()
assetLibrary.writeVideoAtPathToSavedPhotosAlbum(exporter.outputURL, completionBlock: {(url: NSURL!, error: NSError!) in
println("Saved video \(exporter.outputURL)")
if (error != nil) {
println("Error saving video")
}
})
}
一些可能有助於解決您的問題的建議:
檢查為已完成的視頻有效/與磁帶庫兼容這里
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:videoURL]) { [library writeVideoAtPathToSavedPhotosAlbum:videoURL completionBlock:^(NSURL *assetURL, NSError *error){} ]; }
確保傳回的資產 url 不是此處引用的 nil
if(error){ NSLog(@"Error: Domain = %@, Code = %@", [error domain], [error localizedDescription]); } else if(assetURL == nil){ //It's possible for writing to camera roll to fail, without receiving an error message, but assetURL will be nil //Happens when disk is (almost) full NSLog(@"Error saving to camera roll: no error message, but no url returned"); } else { //remove temp file NSError *error; [[NSFileManager defaultManager] removeItemAtURL:fileURL error:&error]; if(error){ NSLog(@"error: %@", [error localizedDescription]); } }
考慮使用 PHPhotoLibrary 來導出視頻
PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(videoURL) let assetPlaceholder = assetRequest.placeholderForCreatedAsset }, completionHandler: { success, error in // check and handle error // do something with your asset local identifier })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.