URLの動画を保存する Swift3

環境

  • Swift
  • Swift3.0
  • swift3
  • Xcode
  • Xcode8
  • avfoundation
  • AVFoundation

説明

アプリを起動したらそのままurlで定義された動画がmacの中のドキュメントフォルダに保存される

実装

//
//  ViewController.swift
//  video-edit
//
//  Created by ryosuke-hujisawa on 2017/10/04.
//  Copyright © 2017年 ryosuke-hujisawa. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // 動画のurlを定義する
        let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
        // 動画URLからアセットを生成
        let videoAsset: AVURLAsset = AVURLAsset(url: url!, options: nil)
        // アセットからトラックを取得
        let videoTrack: AVAssetTrack = videoAsset.tracks(withMediaType: AVMediaType.video)[0]
        let audioTrack: AVAssetTrack = videoAsset.tracks(withMediaType: AVMediaType.audio)[0]
        // ベースとなる動画のコンポジション作成
        let mainComposition : AVMutableComposition = AVMutableComposition()
        // コンポジションのトラック作成
        let compositionVideoTrack: AVMutableCompositionTrack = mainComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)!
        let compositionAudioTrack: AVMutableCompositionTrack = mainComposition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)!
        // コンポジションの設定
        try! compositionVideoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: videoTrack, at: kCMTimeZero)
        try! compositionAudioTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: audioTrack, at: kCMTimeZero)
        // 動画のコンポジションをベースにAVAssetExportを生成
        let assetExport = AVAssetExportSession.init(asset: mainComposition, presetName: AVAssetExportPresetMediumQuality)
        // 生成された動画を保存する場所のurlとファイルの名前を設定(今回はmacの中のDocumentsディレクトリに保存)
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
        let filePath = documentsDirectory.appendingPathComponent("rendered-audio.m4v")
        // エクスポートファイルのビデオタイプの設定
        assetExport?.outputFileType = AVFileType.mov
        //出力されるurlの設定
        assetExport?.outputURL = filePath
        assetExport?.shouldOptimizeForNetworkUse = true
        assetExport?.exportAsynchronously {

            print("finished: \(filePath) :  \(String(describing: assetExport?.status.rawValue)) ")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事