斯威夫特:裁剪和出口视频

时间:2014-12-26 19:14:15

标签: ios video swift crop

我想将视频裁剪成方形,但我无法做到这一点。

我将this code转换为快速,但导出视频后我只获得了黑屏

        var videoComposition: AVMutableVideoComposition = AVMutableVideoComposition()
        videoComposition.frameDuration = CMTimeMake(1, 60)
        videoComposition.renderSize = CGSizeMake(clipVideoTrack.naturalSize.height, clipVideoTrack.naturalSize.height)

        var instruction: AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction()
        instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30))

        var transformer: AVMutableVideoCompositionLayerInstruction =
        AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)

        var t1: CGAffineTransform = CGAffineTransformMakeTranslation(clipVideoTrack.naturalSize.height, 0)
        var t2: CGAffineTransform = CGAffineTransformRotate(t1, CGFloat(M_PI_2))

        var finalTransform: CGAffineTransform = t2

        transformer.setTransform(finalTransform, atTime: kCMTimeZero)

        instruction.layerInstructions = NSArray(object: transformer)
        videoComposition.instructions = NSArray(object: instruction)

        var documentsPath: NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] as NSString

        var exportPath: NSString = documentsPath.stringByAppendingFormat("/xvideo.mov")
        var exportUrl: NSURL = NSURL.fileURLWithPath(exportPath)!


        var exporter = AVAssetExportSession(asset: asset!, presetName: AVAssetExportPresetHighestQuality)
        exporter.videoComposition = videoComposition
        exporter.outputFileType = AVFileTypeQuickTimeMovie
        exporter.outputURL = exportUrl

我缺少什么?

1 个答案:

答案 0 :(得分:4)

您最后错过了导出块,以便使用您创建的AVAssetExportSession执行导出操作:

exporter.exportAsynchronouslyWithCompletionHandler({

    //display video after export is complete, for example...
    let outputURL:NSURL = exporter.outputURL;
    let asset:AVURLAsset = AVURLAsset(URL: outputURL, options: nil)
    let newPlayerItem:AVPlayerItem = AVPlayerItem(asset: asset)

    self.mPlayer = AVPlayer.playerWithPlayerItem(newPlayerItem) as AVPlayer

})