#AVCaptureMovieFileOutputの設定
まず, ファイル出力の設定時点で,向きを変更可能にします。(デフォルトは変更不可)
captureSession.addOutput(videoFileOutput)
let videoDataOuputConnection = videoFileOutput.connection(with: .video)
videoFileOutput.setRecordsVideoOrientationAndMirroringChangesAsMetadataTrack(true, for: videoDataOuputConnection!)
録画開始時にファイル出力の向きをデバイスの向きに合わせます。
let videoDataOuputConnection = videoFileOutput.connection(with: .video)
let orientation = UIDevice.current.orientation
videoDataOuputConnection!.videoOrientation = AVCaptureVideoOrientation(rawValue: orientation.rawValue)!
参考:
How to record landscape video in a portrait application? (Swift 2, iPhone)
#表示映像の設定
回転した際に向きを取得します。
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
coordinator.animateAlongsideTransition(
nil,
completion: {(UIViewControllerTransitionCoordinatorContext) in
//画面の回転後に向きを教える。
if let orientation = self.convertUIOrientation2VideoOrientation({return UIApplication.sharedApplication().statusBarOrientation}) {
videoPreviewLayer?.connection.videoOrientation = orientation
}
}
)
}
func convertUIOrientation2VideoOrientation(f: () -> UIInterfaceOrientation) -> AVCaptureVideoOrientation? {
let v = f()
switch v {
case UIInterfaceOrientation.Unknown:
return nil
default:
return ([
UIInterfaceOrientation.Portrait: AVCaptureVideoOrientation.Portrait,
UIInterfaceOrientation.PortraitUpsideDown: AVCaptureVideoOrientation.PortraitUpsideDown,
UIInterfaceOrientation.LandscapeLeft: AVCaptureVideoOrientation.LandscapeLeft,
UIInterfaceOrientation.LandscapeRight: AVCaptureVideoOrientation.LandscapeRight
])[v]
}
}