Search code examples
swiftavfoundationavassetavmutablecomposition

Video with no audio crashes app on AVMutableComposition()


My app takes a video from a URL and allows you to add text to it, etc. It seems to crash when the video doesn't have any audio to begin with, can't seem to figure this out.

This is what I have when the video is being composed:

let asset = AVAsset(url: URL(string: self.videoURL)!)
let mixComposition = AVMutableComposition()
let videoTrack = mixComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
try! videoTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: asset.duration), of: asset.tracks(withMediaType: .video)[0], at: CMTime.zero)
let audioTrack = mixComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
do {
       try audioTrack!.insertTimeRange(CMTimeRangeMake(start: .zero, duration: asset.duration), of: asset.tracks(withMediaType: .audio)[0], at: CMTime.zero)
   } catch {
       print("error")
   }

It throws on insertTimeRange saying indexPath is out of range.

 [__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray

Solution

  • I figured out how to export the video when the original video has no audio. In case anyone else encounters the same problem.

    let asset = AVAsset(url: URL(string: self.videoURL)!)
    
        let mixComposition = AVMutableComposition()
    
        let videoTrack = mixComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
    
        try! videoTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: asset.duration), of: asset.tracks(withMediaType: .video)[0], at: CMTime.zero)
    
        let audioTrack = mixComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
    
            if let track = asset.tracks(withMediaType: .audio).first {
    
                do {
                    try audioTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: asset.duration), of: track, at: .zero)
                } catch {
                    print("error")
                }
    
            } else {
                mixComposition.removeTrack(audioTrack!)
                print("no audio detected, removed the track")
            }