2016-12-13 7 views
0

私はキャプチャセッションを使用し、カメラが見ているものをプレビューする標準のView Controllerを持っています。これで、ボタンをクリックして、アクションを実行し(下部のsaveVideoアクションで)、ビデオの録画を開始する必要があります。出力のフレームを実際に保存するには、どのようなコードが必要ですか?スウィフトでセッションからビデオをキャプチャする方法は?

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 


    var captureSession = AVCaptureSession(); 
    var sessionOutput = AVCaptureVideoDataOutput(); 
    var previewLayer = AVCaptureVideoPreviewLayer(); 


    override func viewDidAppear(_ animated: Bool) { 
     captureSession.startRunning() 
    } 


    override func viewWillAppear(_ animated: Bool) { 
     let deviceDiscoverySession = AVCaptureDeviceDiscoverySession(deviceTypes: [AVCaptureDeviceType.builtInDuoCamera, AVCaptureDeviceType.builtInTelephotoCamera,AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: AVCaptureDevicePosition.back) 

    for device in (deviceDiscoverySession?.devices)!{ 
     if(device.position == AVCaptureDevicePosition.back){ 

      do{ 
       let input = try AVCaptureDeviceInput(device: device) 

       if captureSession.canAddInput(input){ 

        captureSession.addInput(input) 

       } 

       // sessionOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString) : NSNumber(value: kCVPixelFormatType_420YpCbCr8BiPlanarFullRange as UInt32)] 

       sessionOutput.alwaysDiscardsLateVideoFrames = true 

       if(captureSession.canAddOutput(sessionOutput) == true){ 
        captureSession.addOutput(sessionOutput) 

        let previewLayer: AVCaptureVideoPreviewLayer = { 
         let preview = AVCaptureVideoPreviewLayer(session: self.captureSession) 
         preview?.bounds = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height) 
         preview?.position = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY) 
         preview?.videoGravity = AVLayerVideoGravityResize 
         return preview! 
        }() 

        view.layer.insertSublayer(previewLayer, at: 0) 



       } 

       captureSession.commitConfiguration() 

      } 

      catch{ 
       print("Error") 
      } 


     } 

    } 


} 

    @IBAction func saveVideo(_ sender: Any) { 
    } 
} 

答えて

1

次に、あなたのセッションの異なる状態にトリガーされるデリゲートメソッドを呼び出しますあなたのViewControllerにごAVSessionのデリゲートを設定する必要があります。詳細については

https://developer.apple.com/reference/avfoundation/avcapturesession

を参照してください。具体的captureOutputデリゲートメソッドは、あなたのViewControllerにデリゲートから呼び出されます。

+0

追加する必要があるコードを正確に知っていますか? –

関連する問題