iOS におけるビデオ変換
AVAssetExportSession を使用します。
変換時に指定できるフォーマット
たくさんありますがここでは AVFileTypeMPEG4 を使います。設定できるフォーマットはオフィシャルドキュメント参照。([File Format UTIs](https://developer.apple.com/library/ios/documentation/avfoundation/reference/
AVFoundation_Constants/index.html#//apple_ref/doc/constant_group/File_Format_UTIs ""))
処理の流れ
だいたい以下のようになります。
- AVAsset の生成
- 出力(変換)フォーマットなど変換の設定
- 変換実行(必要であればライブラリに登録)
サンプルコード
下記のコードで iPhone のカメラで録画したビデオを MP4 に変換できました。
環境:iOS 8.1.1, XCode 6.1
let avAsset = AVURLAsset(URL: self.fileMovPathUrl(), options: nil)
let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough)
exportSession.outputFileType = AVFileTypeMPEG4
exportSession.outputURL = self.fileMp4PathUrl()
exportSession.exportAsynchronouslyWithCompletionHandler { () -> Void in
NSFileManager.defaultManager().removeItemAtPath(self.filePath(self.mov_extenstion), error: nil)
switch exportSession.status {
case AVAssetExportSessionStatus.Completed:
let assetsLib = ALAssetsLibrary()
assetsLib.writeVideoAtPathToSavedPhotosAlbum(self.filePathUrl(self.mp4_extenstion), completionBlock: {
(nsurl, error) -> Void in
})
break
case AVAssetExportSessionStatus.Failed:
break
case AVAssetExportSessionStatus.Cancelled:
break
default:
break
}
}