やりたいこと
カメラロールにある動画ファイルをトリムして取得したいのだが、MOV形式になってしまう。
MP4で取り込みたいので、トリム後に変換をするようにする。
import UIKit
import MobileCoreServices
import AVFoundation
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pushedButton(_ sender: AnyObject) {
// カメラロールを表示
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
let controller = UIImagePickerController()
controller.sourceType = UIImagePickerControllerSourceType.photoLibrary
controller.mediaTypes=[kUTTypeMovie as String] // 動画のみ
controller.delegate = self
controller.allowsEditing = true
controller.videoMaximumDuration = 5 // 5秒で動画を切り取る
controller.videoQuality = UIImagePickerControllerQualityType.typeHigh // カメラのハイクォリティのサイズで取得する
self.present(controller, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let url = info[UIImagePickerControllerMediaURL] as? NSURL {
// 一時保持用のパス
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentationDirectory, .userDomainMask, true)[0] as String
let fileName = "tmpVideo.mp4"
let videoPath = documentsPath + fileName
let out: NSURL = NSURL.fileURL(withPath: videoPath) as NSURL
// MOV→MP4に変換
self.converVideo(inputURL: url, outputURL: out, handler: { (exportSession: AVAssetExportSession) in
if (exportSession.status == AVAssetExportSessionStatus.completed) {
// カメラロールに保存する
UISaveVideoAtPathToSavedPhotosAlbum(out.path!, self, nil, nil)
}
})
}
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func converVideo(inputURL: NSURL, outputURL: NSURL, handler: @escaping (_ exportSession: AVAssetExportSession) -> Void) {
do {
// ファイルがあれば削除
try FileManager.default.removeItem(at: outputURL.absoluteURL!)
}
catch _ {
}
let asset:AVURLAsset = AVURLAsset.init(url: inputURL.absoluteURL!, options: nil)
let exportSession:AVAssetExportSession = AVAssetExportSession.init(asset: asset, presetName: AVAssetExportPresetPassthrough)!
exportSession.outputURL = outputURL.absoluteURL;
exportSession.outputFileType = AVFileTypeMPEG4; // MP4形式出力
exportSession.exportAsynchronously(completionHandler: {() -> Void in
handler(exportSession);
})
}
}