在ios中合并两个或多个视频

时间:2015-08-06 16:54:47

标签: ios video merge avvideocomposition

How to combine video clips with different orientation using AVFoundation

我已经接受了上述答案并且进展顺利。但我面临的问题是视频的音频被删除。甚至我的所有视频都有声音。但合并后导出的视频是静音的。谁能帮忙。在此先感谢。

1 个答案:

答案 0 :(得分:0)

我也面临着同样的问题,但是我找到了解决方案。 Swift 4.2版本。

 // Merge All videos.
    func mergeAllVideos(completionHandler: @escaping(Bool)->Void){
        mixComposition = AVMutableComposition.init()

        // To capture video.
        let compositionVideoTrack = mixComposition?.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)

        // To capture audio.
        let compositionAudioTrack = mixComposition?.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
        var nextCliptStartTime: CMTime = CMTime.zero

        // Iterate video array.
        for file_url in Constants.videoFileNameArr{
            // Do Merging here.
            let videoAsset = AVURLAsset.init(url: file_url)
            let timeRangeInAsset = CMTimeRangeMake(start: CMTime.zero, duration: videoAsset.duration);
            do{
                // Merge video.
                try compositionVideoTrack?.insertTimeRange(CMTimeRange(start: CMTime.zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: .video)[0], at: nextCliptStartTime)

                // Merge Audio
                try compositionAudioTrack?.insertTimeRange(CMTimeRange(start: CMTime.zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: .audio)[0], at: nextCliptStartTime)
            }catch{
                print(error)
            }

            // Increment the time to which next clip add.
            nextCliptStartTime = CMTimeAdd(nextCliptStartTime, timeRangeInAsset.duration)
        }

        // Add rotation to make it portrait.
        let rotationTransform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/2))
        compositionVideoTrack!.preferredTransform = rotationTransform

        // Save final file.
        self.saveFinalFile(mixComposition!){
            isDone in
            completionHandler(true)
        }
    }
相关问题