我可以使用AVURLAsset将视频导出到带有音频的MP4吗?

时间:2016-02-16 00:22:39

标签: ios swift audio video

我正在使用代码使用AVURLAsset()打开视频资源,然后我为视频添加水印,并使用AVAssetExportSession()保存它。

在我打开视频之前,它有声音,当我使用AVAssetExportSession()

导出它时声音会丢失

以下是我运行代码的方式

let videoAsset = AVURLAsset(URL: passedVideoURL)

let mixComposition = AVMutableComposition()
let compositionVideoTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
let clipVideoTrack: AVAssetTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo)[0]

do {
    try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), ofTrack: clipVideoTrack, atTime: kCMTimeZero)
} catch {
    print(error)
}

let parentLayer = CALayer()
let videoLayer = CALayer()
parentLayer.frame = CGRectMake(0, 0, videoSize.height, videoSize.width)
videoLayer.frame = CGRectMake(0, 0, videoSize.height, videoSize.width)
parentLayer.addSublayer(videoLayer)
parentLayer.addSublayer(aLayer)


let videoComp = AVMutableVideoComposition()
videoComp.renderSize = CGSize(width: videoSize.height, height: videoSize.width)
videoComp.frameDuration = CMTimeMake(1,30)
videoComp.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, inLayer: parentLayer)

if let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality) {
exporter.outputURL = completeMovieUrl
exporter.shouldOptimizeForNetworkUse = true
exporter.outputFileType = AVFileTypeMPEG4
exporter.videoComposition = videoComp
exporter.exportAsynchronouslyWithCompletionHandler({ () -> Void in
            switch exporter.status {
            case  .Failed:
                print("failed \(exporter.error)")
                //completion(url: nil)
                break
            case .Cancelled:
                print("cancelled \(exporter.error)")
                //completion(url: nil)
                break
            default:
                print("complete")

                let u = exporter.outputURL?.path
                self.dataToPass = NSData(contentsOfFile: u!)!

                //try NSFileManager.removeItemAtPath(u)

                self.performSegueWithIdentifier("sendToFriend", sender: self)

            }
        })
    }

对我而言,似乎我需要导出音频,然后将其合并回视频?我很困惑如何做这个过程。任何方向都非常感谢。

谢谢!

0 个答案:

没有答案