无音频的视频会在AVMutableComposition()上崩溃 [英] Video with no audio crashes app on AVMutableComposition()

查看:91
本文介绍了无音频的视频会在AVMutableComposition()上崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序从URL拍摄视频,并允许您向其中添加文本等.当视频没有任何音频开始时似乎崩溃了,似乎无法弄清楚这一点.

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

它抛出 insertTimeRange indexPath 超出范围.

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

推荐答案

我想出了当原始视频没有音频时如何导出视频的方法.万一其他人遇到同样的问题.

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

这篇关于无音频的视频会在AVMutableComposition()上崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆