2016-10-10 1 views
3

Swift에서 사용자 정의 카메라를 만들려고합니다. 나는 이것에 대한 많은 게시물을 발견하고, 카메라를 열고, "녹음 시작"버튼을 가지고 관리. 이 오류를 찾을 때, 내가 beginSession 기능에서 한 카메라의 품질을 설정하지 않음으로써 발생해야하는데AVFoundation : "활성/활성 연결 없음"으로 인해 레코딩이 시작되지 않습니다.

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[AVCaptureMovieFileOutput startRecordingToOutputFileURL:recordingDelegate:] No active/enabled connections' 

: 그러나, "녹화 시작"버튼을 클릭하면,이 오류가 : 모든 입력이 많은

을 이해할 것이다

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate,AVCaptureFileOutputRecordingDelegate { 


    let imagePicker: UIImagePickerController! = UIImagePickerController() 
    let saveFileName = "/test.mp4" 
    var locationManager : CLLocationManager! = CLLocationManager() 
    var startLocation: CLLocation! 
    //let captureSession = AVCaptureSession() 
    var stillImageOutput: AVCaptureStillImageOutput? 
    var previewLayer: AVCaptureVideoPreviewLayer? 
    let captureSession = AVCaptureSession() 

    // MARK: ViewController methods 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     //var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true) 
     // Do any additional setup after loading the view, typically from a nib. 
     let btn: UIButton = UIButton(frame: CGRectMake((self.view.frame.size.width-350)/2, (self.view.frame.size.height-80), 350, 70)) 
     btn.backgroundColor = hexStringToUIColor("#E53935") 
     btn.setTitle("Go to recording", forState: UIControlState.Normal) 
     btn.addTarget(self, action: "recordVideo:", forControlEvents: UIControlEvents.TouchUpInside) 
     btn.tag = 1    // change tag property 
     self.view.addSubview(btn) // add to view as subview 
     if CLLocationManager.locationServicesEnabled() { 
      locationManager.requestAlwaysAuthorization() 
      locationManager.requestWhenInUseAuthorization() 
      locationManager.delegate = self 
      locationManager.desiredAccuracy = kCLLocationAccuracyBest 
      locationManager.startUpdatingLocation() 
      print(locationManager.location) 
     } 

    } 


    func startCameraFromViewController(viewController: UIViewController, withDelegate delegate: protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>) -> Bool { 
     if UIImagePickerController.isSourceTypeAvailable(.Camera) == false { 
      return false 
     } 

     var cameraController = UIImagePickerController() 
     cameraController.sourceType = .Camera 
     cameraController.mediaTypes = [kUTTypeMovie as NSString as String] 
     cameraController.allowsEditing = false 
     cameraController.delegate = delegate 

     presentViewController(cameraController, animated: true, completion: nil) 
     return true 
    } 

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { 
     let mediaType = info[UIImagePickerControllerMediaType] as! NSString 
     dismissViewControllerAnimated(true, completion: nil) 
     // Handle a movie capture 
     if mediaType == kUTTypeMovie { 
      guard let path = (info[UIImagePickerControllerMediaURL] as! NSURL).path else { return } 
      if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path) { 
       UISaveVideoAtPathToSavedPhotosAlbum(path, self, #selector(ViewController.video(_:didFinishSavingWithError:contextInfo:)), nil) 
      } 
     } 
    } 

    func video(videoPath: NSString, didFinishSavingWithError error: NSError?, contextInfo info: AnyObject) { 
     var title = "Success" 
     var message = "Video was saved" 
     if let _ = error { 
      title = "Error" 
      message = "Video failed to save" 
     } 
     let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) 
     alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)) 
     presentViewController(alert, animated: true, completion: nil) 
    } 

    // MARK: Button handlers 
    // Record a video 
    @IBAction func recordVideo(sender: AnyObject) { 
     let devices = AVCaptureDevice.devices() 
     captureSession.sessionPreset = AVCaptureSessionPresetHigh 
     // captureSession.sessionPreset = kCaptureSessionPresetVideo 
     for device in devices { 
      // Make sure this particular device supports video 
      if (device.hasMediaType(AVMediaTypeVideo)) { 
       // Finally check the position and confirm we've got the back camera 
       if(device.position == AVCaptureDevicePosition.Back) { 
        var captureDevice = device as? AVCaptureDevice 
        if captureDevice != nil { 
         beginSession(captureDevice!) 
        } 
       } 
      } 
     } 
    } 

    func beginSession(captureDevice: AVCaptureDevice) { 
     var err : NSError? = nil 

     var input = AVCaptureDeviceInput?() 
     do { 
      input = try AVCaptureDeviceInput(device: captureDevice) 
     } catch _ { 
      //Error handling, if needed 
     } 
     captureSession.addInput(input) 
     captureSession.sessionPreset = AVCaptureSessionPresetHigh; 

     if err != nil { 
      print("error: \(err?.localizedDescription)") 
     } 

     previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 
     self.view.layer.addSublayer(previewLayer!) 
     previewLayer?.frame = self.view.layer.frame 
     captureSession.startRunning() 
     let btn: UIButton = UIButton(frame: CGRectMake((self.view.frame.size.width-350)/2, (self.view.frame.size.height-80), 350, 70)) 
     btn.backgroundColor = hexStringToUIColor("#E53935") 
     btn.setTitle("Start Recording", forState: UIControlState.Normal) 
     btn.addTarget(self, action: "takeVideoAction", forControlEvents: UIControlEvents.TouchUpInside) 
     btn.tag = 1    // change tag property 
     self.view.addSubview(btn) 

    } 

    func takeVideoAction() { 
     var fileName = "mysavefile.mp4"; 
     let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] 
     var filePath = documentsURL.URLByAppendingPathComponent(fileName) 

     let videoFileOutput = AVCaptureMovieFileOutput() 

     let recordingDelegate:AVCaptureFileOutputRecordingDelegate? = self 
     videoFileOutput.startRecordingToOutputFileURL(filePath, recordingDelegate: recordingDelegate) 
     self.captureSession.addOutput(videoFileOutput) 
     startCameraFromViewController(self, withDelegate: self) 
    } 

    func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) { 
     return 
    } 

    func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) { 
     return 
    } 

} 

: 여기

func beginSession(captureDevice: AVCaptureDevice) { 
     var err : NSError? = nil 

     var input = AVCaptureDeviceInput?() 
     do { 
      input = try AVCaptureDeviceInput(device: captureDevice) 
     } catch _ { 
      //Error handling, if needed 
     } 
     captureSession.addInput(input) 
     captureSession.sessionPreset = AVCaptureSessionPresetHigh; 

     if err != nil { 
      print("error: \(err?.localizedDescription)") 
     } 

     previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 
     self.view.layer.addSublayer(previewLayer!) 
     previewLayer?.frame = self.view.layer.frame 
     captureSession.startRunning() 
     let btn: UIButton = UIButton(frame: CGRectMake((self.view.frame.size.width-350)/2, (self.view.frame.size.height-80), 350, 70)) 
     btn.backgroundColor = hexStringToUIColor("#E53935") 
     btn.setTitle("Start Recording", forState: UIControlState.Normal) 
     btn.addTarget(self, action: "takeVideoAction", forControlEvents: UIControlEvents.TouchUpInside) 
     btn.tag = 1    // change tag property 
     self.view.addSubview(btn) 

    } 

전체 코드 0

답변

3

당신은 당신이 startRecordingToOutputFileURL 전화 전에 캡처 세션 에 비디오 파일 출력을 추가해야합니다

self.captureSession.addOutput(videoFileOutput) 
videoFileOutput.startRecordingToOutputFileURL(filePath, recordingDelegate: recordingDelegate) 
+0

내가 정확히 일을했다,하지만 난 여전히 오류가 발생합니다. 프리셋을 설정하지 않고 비디오를 녹화하는 방법을 알고 있습니까? 때로는 애플이 제안하는 것처럼 activeFormat을 직접 설정해야 할 때도있다. –

+0

새로운 질문을 시작하고 일부 코드를 표시하거나 더 나은 코드를 실행 가능한 코드에 연결할 수 있습니까? –

+0

https://stackoverflow.com/questions/46160407/how-do-i-record-a-video-on-ios-without-using-a-preset 여기 있습니다. –