Swift Video Resizer AVAsset

时间:2016-02-15 06:15:04

标签: ios swift avfoundation avassetwriter avassetexportsession

我有这段代码可以将视频大小调整为1280 x 720到640 x 360 但我想要一个没有裁剪的调整大小。

有没有办法完全调整大小不被裁剪?

这是代码

class func resizer(inputURL : NSURL , completion: (outPutURL : NSURL?) -> Void ){
        let videoAsset = AVAsset(URL: inputURL) as AVAsset
        let clipVideoTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo).first! as AVAssetTrack

        let composition = AVMutableComposition()
        composition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())

        let videoComposition = AVMutableVideoComposition()
        videoComposition.renderSize = CGSizeMake(360,640)
        videoComposition.frameDuration = CMTimeMake(1, 30)

        let instruction = AVMutableVideoCompositionInstruction()
        instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(180, 30))

        let transformer : AVMutableVideoCompositionLayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)

        let t1 = CGAffineTransformMakeTranslation(360, 0)
        let t2 = CGAffineTransformRotate(t1, CGFloat(M_PI_2))
//        let t2 = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
        transformer.setTransform(t2, atTime: kCMTimeZero)
        instruction.layerInstructions = [transformer]
        videoComposition.instructions = [instruction]


        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
        let date = NSDate()

        let tempDir = NSTemporaryDirectory().stringByAppendingString(formatter.stringFromDate(date))
        let d = "\(tempDir).mp4"
        let outputURL = NSURL(fileURLWithPath: d)

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

        exporter?.exportAsynchronouslyWithCompletionHandler({ () -> Void in
            dispatch_async(dispatch_get_main_queue(), {
                completion(outPutURL: outputURL)
            })
        })
    }

2 个答案:

答案 0 :(得分:3)

我认为你正在寻找的东西(没有裁剪的大小调整)也是SCALE视频。尝试使用CGAffineTransformScale / MakeScale。

https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGAffineTransform/#//apple_ref/c/func/CGAffineTransformMakeScale

如果您的比率为0.5(1280/640),您可以尝试:

let t3 = CGAffineTransformScale(t2, 0.5, 0.5)
transformer.setTransform(t3, atTime: kCMTimeZero)

如果看起来不正确,您可能还需要按比例调整平移。

答案 1 :(得分:1)

Swift 4

let playerLayer = AVPlayerLayer(player: player)
let transform = CGAffineTransform.init(scaleX: 0.5, y: 0.5)
playerLayer.setAffineTransform(transform)

LIVE for confirming