ios – 合并视频,但AVAssetExportSession永远不会完成

ios – 合并视频,但AVAssetExportSession永远不会完成,第1张

概述尝试将一些视频合并在一起并将它们作为单个文件导出,从查看教程/示例看,一切似乎都是正确的但是我的AVAssetExportSession似乎永远不会完整,我的视频文件永远不会被导出,任何有关明显错误的帮助我很遗憾会非常感激. 以下是合并视频的功能 注意循环中的’视频’是一个成员变量var videos = [AVAsset](),它会在调用merge之前填充(我会检查它). private fun 尝试将一些视频合并在一起并将它们作为单个文件导出,从查看教程/示例看,一切似乎都是正确的但是我的AVAssetExportSession似乎永远不会完整,我的视频文件永远不会被导出,任何有关明显错误的帮助我很遗憾会非常感激.

以下是合并视频的功能

注意循环中的’视频’是一个成员变量var vIDeos = [AVAsset](),它会在调用merge之前填充(我会检查它).

private func merge(){    // Create AVMutableComposition to contain all AVMutableComposition tracks    var mix_composition = AVMutableComposition()    var total_time_seconds  = 0.0    var tracks = [AVCompositionTrack]()    // Loop over vIDeos and create tracks,keep incrementing total duration    for vIDeo in vIDeos    {        // Create the composition track for this vIDeo        let track = mix_composition.addMutableTrackWithMediaType(AVMediaTypeVIDeo,preferredTrackID: Int32(kCMPersistentTrackID_InvalID))        // Add vIDeo duration to total time        total_time_seconds = total_time_seconds + vIDeo.duration.seconds        // Add track to array of tracks        tracks.append(track)        // Add time range to track        do        {            try track.insertTimeRange(CMTimeRangeMake(kCMTimeZero,vIDeo.duration),ofTrack: vIDeo.tracksWithMediaType(AVMediaTypeVIDeo)[0],atTime: vIDeo.duration)        }        catch _        {        }    }    // Set total time    let preferred_time_scale: Int32 = 600;    let total_time = CMTimeMakeWithSeconds(total_time_seconds,preferred_time_scale)    // Create main instrcution for vIDeo composition    let main_instruction = AVMutableVIDeoCompositionInstruction()    main_instruction.timeRange = CMTimeRangeMake(kCMTimeZero,total_time)    // Create array to hold instructions    var layer_instructions = [AVVIDeoCompositionLayerInstruction]()    // Ensure we have the same number of tracks as vIDeos    if vIDeos.count == tracks.count    {        // Loop number of vIDeos and tracks        for var index = 0; index < vIDeos.count; ++index        {            // Create compositioninstruction for each track            let instruction = vIDeoCompositionInstructionForTrack(tracks[index],asset: vIDeos[index])            if(index == 0)            {                instruction.setopacity(0.0,atTime: vIDeos[index].duration)            }            // Add instruction to instructions array            layer_instructions.append(instruction)        }    }    // Set tack instructions to main instruction    main_instruction.layerInstructions = layer_instructions    let main_composition = AVMutableVIDeoComposition()    main_composition.instructions = [main_instruction]    main_composition.frameDuration = CMTimeMake(1,30)    main_composition.renderSize = CGSize(wIDth: UIScreen.mainScreen().bounds.wIDth,height: UIScreen.mainScreen().bounds.height)    // Get path for Final vIDeo in the current project directory    let documents_url = NSfileManager.defaultManager().URLsForDirectory(.documentDirectory,inDomains: .UserDomainMask)[0]    let final_url = documents_url.URLByAppendingPathComponent("TEST.mp4")    // Create AV Export Session    let exporter = AVAssetExportSession(asset: mix_composition,presetname: AVAssetExportPresetHighestQuality)    exporter!.outputURL = final_url    exporter!.outputfileType = AVfileTypeMPEG4    exporter!.shouldOptimizeforNetworkUse = true    exporter!.vIDeoComposition = main_composition    // Perform the Export    exporter!.exportAsynchronouslyWithCompletionHandler() {        dispatch_async(dispatch_get_main_queue(),{ () -> VoID in            self.exportDIDFinish(exporter!)        })    }}

下面显示了在调用exportAsynchronouslyWithCompletionHandler时调用的exportDIDFinished函数.我进入这个功能,但没有发生任何事情,因为会话状态永远不会完成.

func exportDIDFinish(session: AVAssetExportSession){    if session.status == AVAssetExportSessionStatus.Completed    {        let outputURL = session.outputURL        let library = ALAssetsLibrary()        if library.vIDeoAtPathIsCompatibleWithSavedPhotosAlbum(outputURL)        {            library.writeVIDeoAtPathToSavedPhotosAlbum(outputURL,completionBlock: { (assetURL:NSURL!,error:NSError!) -> VoID in                    if error != nil                    {                        let alert = UIAlertVIEw(Title: "Error",message: "VIDeo Not Saved",delegate: nil,cancelbuttonTitle: "OK")                        alert.show()                    }                    else                    {                        let alert = UIAlertVIEw(Title: "Success",message: "VIDeo Saved",cancelbuttonTitle: "OK")                        alert.show()                    }            })        }    }}

打印会话状态显示它是4失败,所以我打印session.error得到了这个,但我不确定它的含义,任何帮助都会很棒

Optional(Error Domain=AVFoundationErrorDomain Code=-11841 "Operation Stopped" UserInfo={NSLocalizedDescription=Operation Stopped,NSLocalizedFailureReason=The vIDeo Could not be composed.})
解决方法 如果调用了exportDIDFinish但没有任何反应,则会话的状态不是AVAssetExportSessionStatus.Completed.它可能是AVAssetExportSessionStatus.Failed或其他一些值.检查这些值,如果确实失败,请检查session.error属性以获取更多信息.

编辑:如果您想要一个又一个视频播放,请只创建一个AVMutableCompositionTrack.请参阅下面的相关更改:

...    var mix_composition = AVMutableComposition()    // Create the composition track for the vIDeos    let track = mix_composition.addMutableTrackWithMediaType(AVMediaTypeVIDeo,preferredTrackID: Int32(kCMPersistentTrackID_InvalID))    //keep track of total time    var totalTime = kCMTimeZero    for vIDeo in vIDeos    {        // Add time range to track        do        {            let vIDeoTrack = vIDeo.tracksWithMediaType(AVMediaTypeVIDeo)[0]            let vIDeoDuration = vIDeoTrack.duration            let timeRange = CMTimeRangeMake(kCMTimeZero,vIDeoDuration)            try track.insertTimeRange(timeRange,ofTrack: vIDeoTrack,atTime: totalTime)            totalTime = CMTimeAdd(totalTime,vIDeoDuration)        }        catch _        {        }    }    // Create main instruction for vIDeo composition    let main_instruction = AVMutableVIDeoCompositionInstruction()    main_instruction.timeRange = CMTimeRangeMake(kCMTimeZero,totalTime)    // Create array to hold instructions    var layer_instructions = [AVVIDeoCompositionLayerInstruction]()    // Create layer instruction    let layerInstruction = AVMutableVIDeoCompositionLayerInstruction(assetTrack: track)    // Add it to the array    layer_instructions.append(layerInstruction)    ...

您还需要将renderSize调整为适当的值.您的视频大小可能与屏幕大小不同.

总结

以上是内存溢出为你收集整理的ios – 合并视频,但AVAssetExportSession永远不会完成全部内容,希望文章能够帮你解决ios – 合并视频,但AVAssetExportSession永远不会完成所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1105158.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存