Created
September 7, 2018 07:44
-
-
Save buhussain/168e2a76ccfa3a3b918b18b057014aa1 to your computer and use it in GitHub Desktop.
hi am trying to create a function that would take an video URL and return the video but chopped in pieces 5 sec a piece
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import AVFoundation | |
import AssetsLibrary | |
import MobileCoreServices | |
import Photos | |
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{ | |
//MARK: - Constants | |
struct Constants { | |
static let video = "Video" | |
static let alertForPhotoLibraryMessage = "App does not have access to your photos. To enable access, tap settings and turn on Photo Library Access." | |
static let alertForVideoLibraryMessage = "App does not have access to your video. To enable access, tap settings and turn on Video Library Access." | |
} | |
//click of the choose video button. | |
//MARK: - THIS IS MY FUNCTION | |
@IBAction func openImagePicker(_ sender: Any) { | |
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){ | |
let imagePicker = UIImagePickerController() | |
imagePicker.delegate = self | |
imagePicker.sourceType = .photoLibrary | |
imagePicker.mediaTypes = [kUTTypeMovie as String, kUTTypeVideo as String] | |
let status = PHPhotoLibrary.authorizationStatus() | |
switch status { | |
case .authorized: | |
imagePicker.mediaTypes = [kUTTypeMovie as String, kUTTypeVideo as String] | |
print("permission granted") | |
print("am in openImagePicker - status - .authorized") | |
case .denied: | |
print("permission denied") | |
print("am in openImagePicker - status - .denied") | |
case .notDetermined: | |
print("Permission Not Determined") | |
print("am in openImagePicker - status - .notDetermined") | |
PHPhotoLibrary.requestAuthorization({ (status) in | |
if status == PHAuthorizationStatus.authorized{ | |
// photo library access given | |
imagePicker.mediaTypes = [kUTTypeMovie as String, kUTTypeVideo as String] | |
print("access given video library") | |
print("am in openImagePicker - status - .notDetermined - PHAuthorizationStatus.authorized") | |
}else{ | |
print("restriced manually") | |
} | |
}) | |
case .restricted: | |
print("permission restricted to video library") | |
print("am in openImagePicker - status - .restricted") | |
default: | |
// if none of the caces are met then just go out. | |
print("am in openImagePicker - status - default") | |
break | |
} // end switch | |
self.present(imagePicker, animated: true, completion: nil) | |
} | |
} | |
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { | |
self.dismiss(animated: true, completion: nil) | |
} | |
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { | |
let videoURL = info["UIImagePickerControllerMediaURL"] as! URL | |
self.cropVideo1(sourceURL1: videoURL, statTime:10.0, endTime:20.0) | |
self.dismiss(animated: false, completion: nil) | |
} | |
func cropVideo1(sourceURL1: URL, statTime:Float, endTime:Float) | |
{ | |
print("the Start time: \(statTime) , end time is: \(endTime)") | |
let videoAsset: AVAsset = AVAsset(url: sourceURL1) as AVAsset | |
let composition = AVMutableComposition() | |
composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: CMPersistentTrackID()) | |
let videoComposition = AVMutableVideoComposition() | |
videoComposition.renderSize = CGSize(width: 1280, height: 768) | |
videoComposition.frameDuration = CMTimeMake(8, 15) | |
let instruction = AVMutableVideoCompositionInstruction() | |
let length = Float(videoAsset.duration.value) | |
print("length of video is: \(length)") | |
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30)) | |
let start = statTime | |
let end = endTime | |
let exportSession = AVAssetExportSession(asset: videoAsset, presetName: AVAssetExportPresetHighestQuality)! | |
exportSession.outputFileType = .mp4 | |
let startTime = CMTime(seconds: Double(start ), preferredTimescale: 1000) | |
let endTime = CMTime(seconds: Double(end ), preferredTimescale: 1000) | |
print("start time: \(startTime) end time is: \(endTime)") | |
let timeRange = CMTimeRange(start: startTime, end: endTime) | |
exportSession.timeRange = timeRange | |
print("exportSession.timeRange : \(timeRange)") | |
let formatter = DateFormatter() | |
formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'" | |
let date = Date() | |
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString | |
print("documentsPath : \(documentsPath)") | |
let outputPath = "\(documentsPath)/\(formatter.string(from: date)).mp4" | |
print("outputPath : \(outputPath)") | |
let outputURL = URL(fileURLWithPath: outputPath) | |
print("outputURL : \(outputURL)") | |
exportSession.outputURL = outputURL | |
exportSession.outputFileType = .mov | |
print("sucess - am in cropVideo1") | |
exportSession.exportAsynchronously(completionHandler: { () -> Void in | |
DispatchQueue.main.async(execute: { | |
self.exportDidFinish(exportSession) | |
print("sucess am in cropVideo1-exportSession-exportAsynchronously-exportDidFinish") | |
DispatchQueue.main.async(execute: {}); | |
}) | |
}) | |
} | |
func exportDidFinish(_ session: AVAssetExportSession) | |
{ | |
if session.status == AVAssetExportSessionStatus.completed { | |
let outputURL = session.outputURL | |
let library = ALAssetsLibrary() | |
if library.videoAtPathIs(compatibleWithSavedPhotosAlbum: outputURL) { | |
library.writeVideoAtPath(toSavedPhotosAlbum: outputURL) { alAssetURL, error in | |
if error != nil { | |
DispatchQueue.main.async(execute: { | |
print("exportDidFinish: Failed to save video") | |
}) | |
} else { | |
DispatchQueue.main.async(execute: { | |
print("exportDidFinish: Sucessfully saved Video - exportDidFinish - else") | |
}) | |
} | |
} | |
} | |
} | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
//self.imagePicker.delegate = self | |
//give permession to access the photo gallarry. | |
// 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. | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment