Home ios - video capture
Post
Cancel

ios - video capture

Tutorial

Initialise session

1
let captureSession = AVCaptureSession()

Request access to hardware

1
2
3
4
5
6
7
8
9
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo) {
    (granted: Bool) -> Void in
    guard granted else {
        /// Report an error. We didn't get access to hardware.
        return
    }
	
    /// All good, access granted.
}

Find the camera

1
2
3
4
5
6
7
8
9
func device(mediaType: String, position: AVCaptureDevicePosition) -> AVCaptureDevice? {
    guard let devices = AVCaptureDevice.devices(withMediaType: mediaType) as? [AVCaptureDevice] else { return nil }
    
    if let index = devices.index(where: { $0.position == position }) {
        return devices[index]
    }
    
    return nil
}

Add Input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
guard let inputDevice = device(mediaType: AVMediaTypeVideo, position: .front) else { 
	/// Handle an error. We couldn't get hold of the requested hardware.
	return 
}

var captureInput: AVCaptureDeviceInput!

do {
    captureInput = try AVCaptureDeviceInput(device: inputDevice)
}
catch {
    /// Handle an error. Input device is not available.
}

captureSession.beginConfiguration()

guard captureSession.canAddInput(captureInput) else {
    /// Handle an error. We failed to add an input device.
}

captureSession.addInput(captureInput)

Add output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let outputData = AVCaptureVideoDataOutput()

outputData.videoSettings = [
    kCVPixelBufferPixelFormatTypeKey as AnyHashable : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)
]

let captureSessionQueue = DispatchQueue(label: "CameraSessionQueue", attributes: [])
outputData.setSampleBufferDelegate(self, queue: captureSessionQueue)

guard captureSession.canAddOutput(outputData) else {
    /// Handle an error. We failed to add an output device.
}

captureSession.addOutput(outputData)

Start Session

1
2
captureSession.commitConfiguration()
captureSession.startRunning()

Get CMSampleBuffer from Delegate Method

1
2
3
@objc func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
	/// Do more fancy stuff with sampleBuffer.
}
This post is licensed under CC BY 4.0 by the author.