首页 > 代码库 > 自定义相机(一) -- 预览视频流

自定义相机(一) -- 预览视频流

 

 

实现功能:

  自定义视频流,实时预览。

 

运行环境:

  1.  XCODE 5.1.1 

  2.  真机(IPHONE5  ,  IOS6.1.4)

 

 

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>       //导入 - "视频流"


@interface MCViewController : UIViewController

@property (strong, nonatomic) AVCaptureSession * captureSession;    //AVCaptureSession实例
@property (strong, nonatomic) AVCaptureDeviceInput * videoInput;    //持有视频输入实例

@end

 

 

#import "MCViewController.h"

@interface MCViewController ()

@end

@implementation MCViewController




- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //开始扑捉会话
    [self.captureSession startRunning];
}




- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    //停止扑捉会话
    [self.captureSession stopRunning];
}





- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //1.1 创建AVCaptureSession
    self.captureSession = [[AVCaptureSession alloc] init];
    //1.2 指定输入设备。这里使用后摄像头。
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //1.3 创建AVCaptureDeviceInput的实例,将所选设备作为扑捉会话的输入。
    //      此外,在将是其添加到回话前请创建好输入,这里需要做个检查。
    NSError * error = nil;
    self.videoInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (self.videoInput) {
        [self.captureSession addInput:self.videoInput];
    }
    else
    {
        NSLog(@"input error : %@", error);
    }
    
    //2. 创建预览层
    AVCaptureVideoPreviewLayer * previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
    UIView * aView = self.view;
    previewLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [aView.layer addSublayer:previewLayer];
    
}

@end