LoginSignup
30
27

More than 5 years have passed since last update.

Swift で録画したビデオ(mov)を MP4 に変換する

Last updated at Posted at 2014-11-27

iOS におけるビデオ変換

AVAssetExportSession を使用します。

変換時に指定できるフォーマット

たくさんありますがここでは AVFileTypeMPEG4 を使います。設定できるフォーマットはオフィシャルドキュメント参照。(File Format UTIs)

処理の流れ

だいたい以下のようになります。

  1. AVAsset の生成
  2. 出力(変換)フォーマットなど変換の設定
  3. 変換実行(必要であればライブラリに登録)

サンプルコード

下記のコードで 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
    }
}
30
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
27