VideoCaptureProcessor.swift (2517B)
1 // 2 // VideoCaptureProcessor.swift 3 // damus 4 // 5 // Created by Suhail Saqan on 8/5/23. 6 // 7 8 import Foundation 9 import AVFoundation 10 import Photos 11 12 class VideoCaptureProcessor: NSObject { 13 private(set) var movieOutput: AVCaptureMovieFileOutput? 14 15 private let beginHandler: () -> Void 16 private let completionHandler: (VideoCaptureProcessor, URL) -> Void 17 private let videoProcessingHandler: (Bool) -> Void 18 private var session: AVCaptureSession? 19 20 init(movieOutput: AVCaptureMovieFileOutput?, 21 beginHandler: @escaping () -> Void, 22 completionHandler: @escaping (VideoCaptureProcessor, URL) -> Void, 23 videoProcessingHandler: @escaping (Bool) -> Void) { 24 self.beginHandler = beginHandler 25 self.completionHandler = completionHandler 26 self.videoProcessingHandler = videoProcessingHandler 27 self.movieOutput = movieOutput 28 } 29 30 func startCapture(session: AVCaptureSession) { 31 if let movieOutput = self.movieOutput, session.isRunning { 32 let outputFileURL = uniqueOutputFileURL() 33 movieOutput.startRecording(to: outputFileURL, recordingDelegate: self) 34 } 35 } 36 37 func stopCapture() { 38 if let movieOutput = self.movieOutput { 39 if movieOutput.isRecording { 40 movieOutput.stopRecording() 41 } 42 } 43 } 44 45 private func uniqueOutputFileURL() -> URL { 46 let tempDirectory = FileManager.default.temporaryDirectory 47 let fileName = UUID().uuidString + ".mov" 48 return tempDirectory.appendingPathComponent(fileName) 49 } 50 } 51 52 extension VideoCaptureProcessor: AVCaptureFileOutputRecordingDelegate { 53 54 func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { 55 DispatchQueue.main.async { 56 self.beginHandler() 57 } 58 } 59 60 func fileOutput(_ output: AVCaptureFileOutput, willFinishRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { 61 DispatchQueue.main.async { 62 self.videoProcessingHandler(true) 63 } 64 } 65 66 func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { 67 if let error = error { 68 print("Error capturing video: \(error)") 69 return 70 } 71 72 DispatchQueue.main.async { 73 self.completionHandler(self, outputFileURL) 74 self.videoProcessingHandler(false) 75 } 76 } 77 }