如何免费AVAssetExportSession因为很忙?

时间:2019-02-06 13:47:42

标签: swift

在我的项目中,我需要编辑视频。我裁剪(按时间)并裁剪(按尺寸)以生成新视频。 我使用AVAssetExportSession来做到这一点。

代码运行良好,但是尝试20点后出现错误。

func crop(toUrl cropUrl: URL, ratio: Ratio, _ completion: @escaping (_ outputUrl: URL?) -> Void) {
    guard let videoTrack = self.tracks(withMediaType: AVMediaType.video).first else { return }

    let composition = AVMutableVideoComposition()
    composition.renderSize = CGSize(width: (videoTrack.naturalSize.height * ratio.width) + 1.0, height: videoTrack.naturalSize.height)
    composition.frameDuration = CMTimeMake(value: 1, timescale: Int32(roundf(videoTrack.nominalFrameRate)))

    let instruction = AVMutableVideoCompositionInstruction()
    instruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: self.duration)

    let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
    let transform = CGAffineTransform(translationX: -(videoTrack.naturalSize.width - videoTrack.naturalSize.height * ratio.width) / 2, y: 0.0)
    layerInstruction.setTransform(transform, at: CMTime.zero)

    instruction.layerInstructions = [layerInstruction]
    composition.instructions = [instruction]

    let exportSession = AVAssetExportSession(asset: self, presetName: AVAssetExportPreset1280x720)!
    exportSession.videoComposition = composition
    exportSession.outputURL = cropUrl
    exportSession.outputFileType = AVFileType.mov

    exportSession.exportAsynchronously( completionHandler: { () -> Void in
        guard exportSession.status == .completed else {
            print(exportSession.error.debugDescription)

            DispatchQueue.main.async {
                completion(nil)
            }

            return
        }

        DispatchQueue.main.async {
            completion(exportSession.outputURL)
        }
    })
}

错误:

AVFoundationErrorDomain代码= -11839“无法解码”并且NSLocalizedFailureReason =该媒体所需的解码器忙。NSLocalizedRecoverySuggestion =停止任何其他解码媒体的操作,然后重试。NSLocalizedDescription =无法解码

那么我该如何访问AVAssetExportSession中仍在处理的数据?我可以释放它们吗?还有另一种方法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您是否同时运行多个сrop()函数?如果是这样,我建议您创建一个最大并行操作数等于1的队列,然后将func作物包装到操作中。