Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Video Buffer Output in Swift

My goal is to take the video buffer and ultimately convert it to NSData but I do not understand how to access the buffer properly. I have the captureOutput function but I have not been successful if converting the buffer and I'm not sure I am actually collecting anything in the buffer. This is all using swift code, I have found some examples using Objective-C but I am not able to understand the Obj-c code well enough to figure it out.

var captureDevice : AVCaptureDevice?
var videoCaptureOutput = AVCaptureVideoDataOutput()
var bounds: CGRect = UIScreen.mainScreen().bounds
let captureSession = AVCaptureSession()
var captureConnection: AVCaptureMovieFileOutput?
override func viewDidLoad() {
    super.viewDidLoad()
    captureSession.sessionPreset = AVCaptureSessionPreset640x480
    let devices = AVCaptureDevice.devices()
 for device in devices {
        if (device.hasMediaType(AVMediaTypeVideo)) {
            if device.position == AVCaptureDevicePosition.Back {
                captureDevice = device as? AVCaptureDevice
                if captureDevice != nil {
                    beginSession()
                }
            }
        }
    }
}

func beginSession() {
    var screenWidth:CGFloat = bounds.size.width
    var screenHeight:CGFloat = bounds.size.height
    var err : NSError? = nil
    captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err)!)
  if err != nil {
        println("Error: \(err?.localizedDescription)")
    }
videoCaptureOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey:kCVPixelFormatType_32BGRA]
    videoCaptureOutput.alwaysDiscardsLateVideoFrames = true
captureSession.addOutput(videoCaptureOutput)
videoCaptureOutput.setSampleBufferDelegate(self, queue: dispatch_queue_create("sample buffer delegate", DISPATCH_QUEUE_SERIAL))
    if captureSession.canAddOutput(self.videoCaptureOutput) {
        captureSession.addOutput(self.videoCaptureOutput)
    }
func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
      // I think this is where I can get the buffer info.
 }

Not sure what happened to the formatting, i can post again if I need to.

I got you :) to add formatting use

"```Swift"

<code>

"```"

Note: With out the ""