3
3

More than 3 years have passed since last update.

指定した間隔で連写するカメラをつくります。

AVCaptureSessionの構成。
PhotoOutputではなく、VideoOutputのフレームを取得します。

var captureSession = AVCaptureSession()
var previewView = UIView()
var previewLayer:AVCaptureVideoPreviewLayer?
let videoDataOutput = AVCaptureVideoDataOutput()

let videoDevice = AVCaptureDevice.default(for: AVMediaType.video)
let videoInput = try! AVCaptureDeviceInput.init(device: videoDevice!)

captureSession.beginConfiguration()
captureSession.addInput(videoInput)
videoDataOutput.setSampleBufferDelegate(self, queue: videoDataOutputQueue)
videoDataOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)]
videoDataOutput.alwaysDiscardsLateVideoFrames = true
captureSession.addOutput(videoDataOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.frame = previewView.bounds
previewView.layer.addSublayer(previewLayer!)
captureSession.commitConfiguration()
let captureConnection = videoDataOutput.connection(with: .video)
captureConnection?.videoOrientation = .portrait
captureConnection?.isEnabled = true
captureSession.startRunning()

AVCaptureVideoOutputDelegateのCaptureOutputメソッド内で、取得したフレームを保存します。

var isGettingBuffer = false

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    if isGettingBuffer{         
        guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
            return
        }
        let image = UIImage(ciImage: CIImage(cvImageBuffer: pixelBuffer))
        let data = image.jpegData(compressionQuality: 1)
        PHPhotoLibrary.shared().performChanges({
            let creationRequest = PHAssetCreationRequest.forAsset()
            creationRequest.addResource(with: .photo,
                                        data: data!,
                                        options: nil)
        })
        isGettingBuffer = false
    }
}

指定した間隔でフレームを保存するようにタイマーを設定します。

Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (Timer) in
            //好きなキャプチャ間隔を指定する。ここでは1秒。
            self.isGettingBuffer = true
        }

***
Core MLを使ったアプリを作っています。
機械学習関連の情報を発信しています。

Twitter
MLBoysチャンネル
Medium

相棒
note

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3