在 iOS 中将两个带有音频和视频的视频合并在一起

Merge two videos with audio and video together in iOS

我正在尝试将 AVFoundation 中的两个视频合并在一起。 我正在使用 AVMutableComposition 并将两个曲目添加到合成中,从而生成最终视频,其中我有第一个视频及其音频,然后是第二个音频但没有视频。

如何获取两个曲目的音频和视频?

谢谢

let composition = AVMutableComposition()
        let audioTrack: AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)!
        let videoTrack: AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)!
        
        let audioTrack2: AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)!
        let videoTrack2: AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)!
        var outputURL = documentDirectory.appendingPathComponent("output-temp")
        
        do {
            try! audioTrack.insertTimeRange(CMTimeRangeFromTimeToTime(start: startTime, end: endTime), of: asset.tracks(withMediaType: AVMediaType.audio)[0], at: CMTime.zero)
            
            try! videoTrack.insertTimeRange(CMTimeRangeFromTimeToTime(start: startTime, end: endTime), of: asset.tracks(withMediaType: AVMediaType.video)[0], at: CMTime.zero)
            
            try! audioTrack2.insertTimeRange(CMTimeRangeFromTimeToTime(start: startTime, end: asset2.duration), of: asset2.tracks(withMediaType: AVMediaType.audio)[0], at: CMTime.invalid)
            
            try! videoTrack2.insertTimeRange(CMTimeRangeFromTimeToTime(start: startTime, end: asset2.duration), of: asset2.tracks(withMediaType: AVMediaType.video)[0], at: CMTime.invalid)
            
            try manager.createDirectory(at: outputURL, withIntermediateDirectories: true, attributes: nil)
        
            let id = "id-\(Int.random(in: 0...199))"
            let mediaType = "mp4"
            outputURL = outputURL.appendingPathComponent("preVideo-\(id).\(mediaType)")
            
        } catch let error {
            print(error)
        }

问题是您正在向合成中添加第二个视频轨道。您需要将这两个视频插入到 相同的 视频轨道中。只需删除您的 let videoTrack2 并从那里开始。