我使用此方法合并音频和视频文件,其大小与先前录制和分开存储的大小相同。
func mergeVideoAudio(audioURL: NSURL, moviePathUrl: NSURL, savePathUrl: NSURL) {
let composition = AVMutableComposition()
let trackVideo:AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())
let trackAudio:AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
let option = NSDictionary(object: true, forKey: "AVURLAssetPreferPreciseDurationAndTimingKey")
let sourceAsset = AVURLAsset(URL: moviePathUrl, options: option as? [String : AnyObject])
let audioAsset = AVURLAsset(URL: audioURL, options: option as? [String : AnyObject])
let video = sourceAsset.tracksWithMediaType(AVMediaTypeVideo)
let audio = audioAsset.tracksWithMediaType(AVMediaTypeAudio)
let assetTrack:AVAssetTrack = video[0] as AVAssetTrack
let assetTrackAudio:AVAssetTrack = audio[0] as AVAssetTrack
let videoDuration:CMTime = assetTrack.timeRange.duration
let audioDuration:CMTime = assetTrackAudio.timeRange.duration
do {
try trackVideo.insertTimeRange(CMTimeRangeMake(kCMTimeZero,videoDuration), ofTrack: assetTrack, atTime: kCMTimeZero)
try trackAudio.insertTimeRange(CMTimeRangeMake(kCMTimeZero, audioDuration), ofTrack: assetTrackAudio, atTime: kCMTimeZero)
} catch{
print("error while merging audio and video")
}
}
let assetExport: AVAssetExportSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)!
assetExport.outputFileType = AVFileTypeQuickTimeMovie
assetExport.outputURL = savePathUrl
assetExport.shouldOptimizeForNetworkUse = true
assetExport.exportAsynchronouslyWithCompletionHandler({
() -> Void in
switch assetExport.status {
case AVAssetExportSessionStatus.Completed:
print("completed")
case AVAssetExportSessionStatus.Failed:
print("failed \(assetExport.error)")
case AVAssetExportSessionStatus.Cancelled:
print("cancelled \(assetExport.error)")
default:
print("default export status")
}
})
}
有时(每8-9次捕获)它会给我这个错误:
failed Optional(Error Domain=AVFoundationErrorDomain Code=-11820 "Cannot Complete Export" UserInfo={NSLocalizedDescription=Cannot Complete Export, NSLocalizedRecoverySuggestion=Try exporting again.})
我尝试过更改视频编码,音频和视频长度,导出选项等,但没有成功。
合并后,我用AVPlayer显示结果预览,当发生此错误时,解码时显然会失败。