【发布时间】:2018-01-11 05:09:27
【问题描述】:
我正在尝试使用 AVFoundation 加入 2 个视频剪辑。出于测试目的,我在这里尝试加载单个视频剪辑,将其视频和音轨添加到合成中,然后使用 AVAssetExportSession 导出。
当我运行下面的代码时,会输出“Exporting”,但永远不会执行导出回调。此外,如果我定期检查导出进度 (print(exporter.progress)),我发现进度始终为 0.0,即使在几分钟后也是如此。如果我打印状态,我发现它正在“等待”某事。
// URL to video file
let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("video.mov")
// Create composition and tracks
let comp = AVMutableComposition()
let videoTrack = comp.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)
let audioTrack = comp.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)
// Create asset from file
let asset = AVAsset(url: fileURL)
// Insert video
try! videoTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, asset.duration), of: asset.tracks(withMediaType: AVMediaType.video)[0] as AVAssetTrack, at: kCMTimeZero)
// Insert audio
try! audioTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, asset.duration), of: asset.tracks(withMediaType: AVMediaType.audio)[0] as AVAssetTrack, at: kCMTimeZero)
// Delete existing movie file if exists
let finalURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("FINAL.mov")
try? FileManager.default.removeItem(at: finalURL)
// Create the exporter
exporter = AVAssetExportSession(asset: comp, presetName: AVAssetExportPresetLowQuality)
exporter.outputURL = finalURL
exporter.outputFileType = AVFileType.mov
print("Exporting")
exporter.exportAsynchronously(completionHandler: {
// This statement is never reached
print(self.exporter.error)
})
从未抛出任何错误。似乎出口永远不会开始。我不确定它在等什么。
编辑:发生了一些令人毛骨悚然的事情。如果我重新启动手机然后运行代码,它就可以工作。但它正好工作 1 次。如果我再次运行它,则不会像往常一样发生任何事情。但是当我重新启动手机并再次运行它时,它又可以工作了。
编辑 2:我在别人的手机上试过,每次都能可靠运行。我的手机到底出了什么问题?
【问题讨论】:
-
这是在设备上还是模拟器上?您是否配置了
AVAudioSession? -
这是在设备上。不,我目前没有使用 AVAudioSession。
-
而
exportSession是一个类变量?它不会超出范围吗? -
正确。如果重要的话——我正在使用
AVCaptureSession和AVAssetWriter不断录制5 秒的剪辑。目标是将其中 2 个剪辑连接在一起(我仍在录制新剪辑) -
我发现了一些有趣的东西。如果我重新启动手机,该代码将只运行一次。它工作一次,然后再没有,直到我重新启动手机。这对我来说非常奇怪。
标签: ios swift avfoundation