在阅读了几个这样的教程并查看了其他代码导出视频后,我们仍然无法解决问题。
有时新视频会导出到相机胶卷,有时则不会。我们甚至无法始终如一地重现该问题。
我们可以想象的唯一问题是 ifNSFileManager.defaultManager().removeItemAtPath
不是阻塞调用,但没有文档表明它是异步的,所以我们假设情况并非如此。
每次,闭包println
内的“保存的视频”writeVideoAtPathToSavedPhotosAlbum
都会被调用,这表明视频已成功写入相机胶卷,但我们在那里看不到视频。
有关如何排除故障的建议?
代码:
// -- 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")
}
})
}