天天看點

Your first video app: show a video preview on screen

This is a very basic demo showing video preview on screen using AVFoundation framework.  To learn more about development with AVFoundation, visit http://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/00_Introduction.html

1. Create a single view iOS project with XCode

2. Add the following line to ViewController.m

#import <AVFoundation/AVFoundation.h>

3. Add the following codes to ViewDidLoad() function in ViewController.m

    // create and initialize AVCaptureSession instance

    AVCaptureSession *session = [[AVCaptureSession alloc] init];

    [session setSessionPreset:AVCaptureSessionPresetHigh];

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    NSError *error = nil;

    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];

    if (deviceInput) {

        [session addInput:deviceInput];

        // show video preview layer

        [self showVideoPreviewWithSession:session];

        [session startRunning];

    }

    else {

        // handle failure

    }

4. Add the following function to ViewController.m

- (void)showVideoPreviewWithSession:(AVCaptureSession *)session

{

    AVCaptureVideoPreviewLayer *previewLayer = nil;

    previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];

    [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

    CALayer *rootLayer = [[self view] layer];

    [rootLayer setMasksToBounds:YES];

    [previewLayer setFrame:CGRectMake(-70, 0, rootLayer.bounds.size.height, rootLayer.bounds.size.height)];

    [rootLayer insertSublayer:previewLayer atIndex:0];

}

5. Double click project name to open project settings -> Build Phases, click "+" in Link Binary with Libraries section and add AVFoundation.framework to linking libraries.  By default, XCode only includes some basic libraries.  Without proper configuration, the builder will give some linker error. 

6. Build and run the app on iOS device. (NOTE: This works on real iOS device, showing the video stream preview on screen when you start the application The iphone simulator does not show anything but a white screen. Not sure if it is possible with simulator.