Jun Fang
Jun Fang

Reputation: 351

Get several video frames as fast as possible using iphone's camera with swift

My goal is that when user press a button, several video frames are captured as fast as possible and finally saved into photo album in iphone.

I am not familiar with swift, so I use a very crappy implementation. I define a int number with 0, and change it to the frame numbers that I want to capture when user presses the button.

var number:Int? = 0

@IBAction func takeFrames(sender: UIButton) {
    self.number=5;
}

then in the delegate I save these frames to photo album:

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
    if(number>0) {
        let rawImage:UIImage = self.imageFromSampleBuffer(sampleBuffer)
        let img = UIImagePNGRepresentation(rawImage)
        let pngImg = UIImage.init(data: img!)
        UIImageWriteToSavedPhotosAlbum(pngImg!, nil, nil, nil)
        print("PNG frame write to photo album successfully")
        number = number!-1;
    }

}

My question is:

1) Can I use more elegant and safe way to use button pressing to control the frames capturing?

2) Currently, I save the frame one by one, so I don't achieve the goal that capture frames as soon as possible, can I capture all frames that I need and save them into photo album once in the end?

Thanks in advance.

Upvotes: 0

Views: 245

Answers (1)

Keaton Burleson
Keaton Burleson

Reputation: 508

Try doing this:

    let imageArray: NSMutableArray?
    for _ in 0 ..< 5  {
        let rawImage:UIImage = self.imageFromSampleBuffer(sampleBuffer)
        let img = UIImagePNGRepresentation(rawImage)
        let pngImg = UIImage.init(data: img!)
        imageArray?.addObject(pngImg!)

    }
    for image in imageArray! {
        UIImageWriteToSavedPhotosAlbum(image as! UIImage, nil, nil, nil)
    }
    print("PNG frame write to photo album successfully")

Swift can sometimes be confusing in for statements. This will take '5' images.

Upvotes: 0

Related Questions