2016-12-04 5 views
0

ビデオを正方形のUIViewに録画していますが、ビデオをエクスポートすると1080x1920のフルスクリーンになりました。ビデオをフルスクリーンから1:1の正方形に縮小する方法が不思議です...クロップビデオスウィフト

session = AVCaptureSession() 
     for device in AVCaptureDevice.devices() { 

      if let device = device as? AVCaptureDevice , device.position == AVCaptureDevicePosition.back { 

       self.device = device 
      } 
     } 

     for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeAudio) { 
      let device = device as? AVCaptureDevice 
      let audioInput = try! AVCaptureDeviceInput(device: device) 
      session?.addInput(audioInput) 
     } 

     do { 

      if let session = session { 
       videoInput = try AVCaptureDeviceInput(device: device) 

       session.addInput(videoInput) 

       videoOutput = AVCaptureMovieFileOutput() 
       let totalSeconds = 60.0 //Total Seconds of capture time 
       let timeScale: Int32 = 30 //FPS 

       let maxDuration = CMTimeMakeWithSeconds(totalSeconds, timeScale) 


       videoOutput?.maxRecordedDuration = maxDuration 
       videoOutput?.minFreeDiskSpaceLimit = 1024 * 1024//SET MIN FREE SPACE IN BYTES FOR RECORDING TO CONTINUE ON A VOLUME 

       if session.canAddOutput(videoOutput) { 
        session.addOutput(videoOutput) 
       } 


       let videoLayer = AVCaptureVideoPreviewLayer(session: session) 
       videoLayer?.frame = self.videoPreview.bounds 

       videoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill 

       self.videoPreview.layer.addSublayer(videoLayer!) 

       session.startRunning() 

が、私は彼らは非常に有用見つけ、そしてそれらのほとんどがobj Cにあるいくつかの他の記事を見てなくて...

の場合:私は、私のビデオカメラを設定していますどのようにここで

です誰でも私を助けたり、正しい方向に私を置くことができます。それは非常に感謝しています!

答えて

2

まず、AVCaptureFileOutputRecordingDelegateを使用する必要があります。

ビデオの録画が完了したら、具体的にはfunc capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!)メソッドを使用してクロップ処理を実行します。

私が一度実装したクロッピング機能の例です。記録されたビデオのURLを渡す必要があります。クロッピング処理が完了したら、クロップされたビデオの新しいURLを返すために使用されるコールバックを渡す必要があります。

func cropVideo(_ outputFileUrl: URL, callback: @escaping (_ newUrl: URL) ->()) 
    { 
     // Get input clip 
     let videoAsset: AVAsset = AVAsset(url: outputFileUrl) 
     let clipVideoTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo).first! as AVAssetTrack 

     // Make video to square 
     let videoComposition = AVMutableVideoComposition() 
     videoComposition.renderSize = CGSize(width: clipVideoTrack.naturalSize.height, height: clipVideoTrack.naturalSize.height) 
     videoComposition.frameDuration = CMTimeMake(1, self.framesPerSecond) 

     // Rotate to portrait 
     let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack) 
     let transform1 = CGAffineTransform(translationX: clipVideoTrack.naturalSize.height, y: -(clipVideoTrack.naturalSize.width - clipVideoTrack.naturalSize.height)/2) 
     let transform2 = transform1.rotated(by: CGFloat(M_PI_2)) 
     transformer.setTransform(transform2, at: kCMTimeZero) 

     let instruction = AVMutableVideoCompositionInstruction() 
     instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(self.intendedVideoLength, self.framesPerSecond)) 

     instruction.layerInstructions = [transformer] 
     videoComposition.instructions = [instruction] 

     // Export 
     let croppedOutputFileUrl = URL(fileURLWithPath: FileManager.getOutputPath(String.random())) 
     let exporter = AVAssetExportSession(asset: videoAsset, presetName: AVAssetExportPresetHighestQuality)! 
     exporter.videoComposition = videoComposition 
     exporter.outputURL = croppedOutputFileUrl 
     exporter.outputFileType = AVFileTypeQuickTimeMovie 

     exporter.exportAsynchronously(completionHandler: {() -> Void in 
      DispatchQueue.main.async(execute: { 
       callback(croppedOutputFileUrl) 
      }) 
     }) 
    } 

また、ここに私のgetOutputPathメソッドの実装です:

func getOutputPath(_ name: String) -> String 
{ 
    let documentPath = NSSearchPathForDirectoriesInDomains(  .documentDirectory, .userDomainMask, true)[ 0 ] as NSString 
    let outputPath = "\(documentPath)/\(name).mov" 
    return outputPath 
} 

は、この情報がお役に立てば幸いですが。

+0

FileManager.getOutputPath(String.random()が何であるか質問してもいいですか?) –

+0

Hey Jack、FileManagerはファイル関連のものを処理するカスタムクラスです。FileManager.getOutputPath (String.random())は、ランダムなStringファイル名をとり、そのファイルへのurlパスを出力します。それに応じて私の答えを更新しました。 – AndreasLukas

+0

それは良いと思われます。 +1を今すぐ受け入れます。ありがとうたくさんあります。 –