Video with no audio crashes app on AVMutableComposition()

六月ゝ 毕业季﹏ 提交于 2020-12-12 06:07:16

问题


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

回答1:


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")
        }


来源:https://stackoverflow.com/questions/56729461/video-with-no-audio-crashes-app-on-avmutablecomposition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!