目的:打开、关闭前置摄像头,绘制图像,并获取摄像头的二进制数据。
需要的库
AVFoundation.framework 、CoreVideo.framework 、CoreMedia.framework 、QuartzCore.framework
该摄像头捕抓必须编译真机的版本,模拟器下编译不了。
函数说明

- (void)createControl
{
// UI界面控件的创建
}

- (AVCaptureDevice *)getFrontCamera;
获取前置摄像头设备
- (void)startVideoCapture;
打开摄像头并开始捕捉图像
其中代码:
AVCaptureVideoPreviewLayer* previewLayer = [AVCaptureVideoPreviewLayer layerWithSession: self->avCaptureSession];
previewLayer.frame = localView.bounds;
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self->localView.layer addSublayer: previewLayer]; 
为把图片画到UIView里面

- (void)stopVideoCapture:(id)arg;

关闭摄像头,停止捕抓图像
其中代码:

for(UIView*viewinself->localView.subviews) {
[viewremoveFromSuperview];
}

为移除摄像头图像的View
详情见代码,代码拷过去可以直接使用      Over!!!!

代码:
头文件:

//
//  AVCallController.h
//  Pxlinstall
//
//  Created by Lin Charlie C. on 11-3-24.
//  Copyright 2011  xxxx. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface AVCallController : UIViewController <AVCaptureVideoDataOutputSampleBufferDelegate>
{
//UI
UILabel*labelState;
UIButton*btnStartVideo;
UIView*localView;

AVCaptureSession* avCaptureSession;
AVCaptureDevice *avCaptureDevice;
BOOLfirstFrame; //是否为第一帧
intproducerFps;

}
@property (nonatomic, retain) AVCaptureSession *avCaptureSession;
@property (nonatomic, retain) UILabel *labelState;

- (void)createControl;
- (AVCaptureDevice *)getFrontCamera;
- (void)startVideoCapture;
- (void)stopVideoCapture:(id)arg;
@end
/
/
/
实现文件:
    //
//  AVCallController.m
//  Pxlinstall
//
//  Created by Lin Charlie C. on 11-3-24.
//  Copyright 2011  高鸿移通. All rights reserved.
//

#import "AVCallController.h"

@implementation AVCallController

@synthesize avCaptureSession;
@synthesize labelState;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/
-(id)init
{
if(self= [superinit])
{
firstFrame= YES;
producerFps= 50;
}
returnself;
}

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
[superloadView];
[selfcreateControl];
}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientati***** other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientati*****.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[superdidReceiveMemoryWarning];

// Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
[superviewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark createControl
- (void)createControl
{
//UI展示
self.view.backgroundColor= [UIColorgrayColor];
labelState= [[UILabelalloc] initWithFrame:CGRectMake(10, 20, 220, 30)];
labelState.backgroundColor= [UIColorclearColor];
[self.viewaddSubview:labelState];
[labelStaterelease];

btnStartVideo= [[UIButtonalloc] initWithFrame:CGRectMake(20, 350, 80, 50)];
[btnStartVideosetTitle:@"Star"forState:UIControlStateNormal];

[btnStartVideosetBackgroundImage:[UIImageimageNamed:@"Images/button.png"] forState:UIControlStateNormal];
[btnStartVideoaddTarget:selfaction:@selector(startVideoCapture) forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:btnStartVideo];
[btnStartVideorelease];

UIButton* stop = [[UIButtonalloc] initWithFrame:CGRectMake(120, 350, 80, 50)];
[stop setTitle:@"Stop"forState:UIControlStateNormal];

[stop setBackgroundImage:[UIImageimageNamed:@"Images/button.png"] forState:UIControlStateNormal];
[stop addTarget:selfaction:@selector(stopVideoCapture:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:stop];
[stop release];

localView= [[UIViewalloc] initWithFrame:CGRectMake(40, 50, 200, 300)];
[self.viewaddSubview:localView];
[localViewrelease];

}
#pragma mark -
#pragma mark VideoCapture
- (AVCaptureDevice *)getFrontCamera
{
//获取前置摄像头设备
NSArray *cameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in cameras)
{
        if (device.position == AVCaptureDevicePositionFront)
            return device;
    }
    return [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

}
- (void)startVideoCapture
{
//打开摄像设备,并开始捕抓图像
[labelStatesetText:@"Starting Video stream"];
if(self->avCaptureDevice|| self->avCaptureSession)
{
[labelStatesetText:@"Already capturing"];
return;
}

if((self->avCaptureDevice = [self getFrontCamera]) == nil)
{
[labelStatesetText:@"Failed to get valide capture device"];
return;
}

NSError *error = nil;
    AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:self->avCaptureDevice error:&error];
    if (!videoInput)
{
[labelStatesetText:@"Failed to get video input"];
self->avCaptureDevice= nil;
        return;
    }

self->avCaptureSession = [[AVCaptureSession alloc] init];
    self->avCaptureSession.sessionPreset = AVCaptureSessionPresetLow;
    [self->avCaptureSession addInput:videoInput];

// Currently, the only supported key is kCVPixelBufferPixelFormatTypeKey. Recommended pixel format choices are 
// kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange or kCVPixelFormatType_32BGRA. 
// On iPhone 3G, the recommended pixel format choices are kCVPixelFormatType_422YpCbCr8 or kCVPixelFormatType_32BGRA.
//
    AVCaptureVideoDataOutput *avCaptureVideoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
NSDictionary*settings = [[NSDictionaryalloc] initWithObjectsAndKeys:
//[NSNumber numberWithUnsignedInt:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange], kCVPixelBufferPixelFormatTypeKey,
[NSNumbernumberWithInt:240], (id)kCVPixelBufferWidthKey,
                              [NSNumber numberWithInt:320], (id)kCVPixelBufferHeightKey,
  nil];
    avCaptureVideoDataOutput.videoSettings = settings;
    [settings release];
    avCaptureVideoDataOutput.minFrameDuration = CMTimeMake(1, self->producerFps);
/*We create a serial queue to handle the processing of our frames*/
dispatch_queue_tqueue = dispatch_queue_create("org.doubango.idoubs", NULL);
    [avCaptureVideoDataOutput setSampleBufferDelegate:self queue:queue];
    [self->avCaptureSession addOutput:avCaptureVideoDataOutput];
    [avCaptureVideoDataOutput release];
dispatch_release(queue);

AVCaptureVideoPreviewLayer* previewLayer = [AVCaptureVideoPreviewLayer layerWithSession: self->avCaptureSession];
previewLayer.frame = localView.bounds;
previewLayer.videoGravity= AVLayerVideoGravityResizeAspectFill;

[self->localView.layer addSublayer: previewLayer];

self->firstFrame= YES;
    [self->avCaptureSession startRunning];

[labelStatesetText:@"Video capture started"];

}
- (void)stopVideoCapture:(id)arg
{
//停止摄像头捕抓
if(self->avCaptureSession){
[self->avCaptureSession stopRunning];
self->avCaptureSession= nil;
[labelStatesetText:@"Video capture stopped"];
}
self->avCaptureDevice= nil;
//移除localView里面的内容
for(UIView*viewinself->localView.subviews) {
[viewremoveFromSuperview];
}
}
#pragma mark -
#pragma mark AVCaptureVideoDataOutputSampleBufferDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection 
{
//捕捉数据输出 要怎么处理虽你便
CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
/*Lock the buffer*/
if(CVPixelBufferLockBaseAddress(pixelBuffer, 0) == kCVReturnSuccess)
{
        UInt8 *bufferPtr = (UInt8 *)CVPixelBufferGetBaseAddress(pixelBuffer);
        size_t buffeSize = CVPixelBufferGetDataSize(pixelBuffer);

if(self->firstFrame)

if(1)
{
//第一次数据要求:宽高,类型
int width = CVPixelBufferGetWidth(pixelBuffer);
int height = CVPixelBufferGetHeight(pixelBuffer);

int pixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer);
switch (pixelFormat) {
casekCVPixelFormatType_420YpCbCr8BiPlanarVideoRange:
//TMEDIA_PRODUCER(producer)->video.chroma = tmedia_nv12; // iPhone 3GS or 4
NSLog(@"Capture pixel format=NV12");
break;
casekCVPixelFormatType_422YpCbCr8:
//TMEDIA_PRODUCER(producer)->video.chroma = tmedia_uyvy422; // iPhone 3
NSLog(@"Capture pixel format=UYUY422");
break;
default:
//TMEDIA_PRODUCER(producer)->video.chroma = tmedia_rgb32;
NSLog(@"Capture pixel format=RGB32");
break;
}

self->firstFrame = NO;
}
}
/*We unlock the buffer*/
CVPixelBufferUnlockBaseAddress(pixelBuffer, 0); 
    }
/*We create an autorelease pool because as we are not in the main_queue our code is
 not executed in the main thread. So we have to create an autorelease pool for the thread we are in*/
// NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// 
//    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); 
//    /*Lock the image buffer*/
//    CVPixelBufferLockBaseAddress(imageBuffer,0); 
//    /*Get information about the image*/
//    uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer); 
//    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); 
//    size_t width = CVPixelBufferGetWidth(imageBuffer); 
//    size_t height = CVPixelBufferGetHeight(imageBuffer);  
//    
//    /*Create a CGImageRef from the CVImageBufferRef*/
//    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
//    CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
//    CGImageRef newImage = CGBitmapContextCreateImage(newContext); 
// 
//    /*We release some components*/
//    CGContextRelease(newContext); 
//    CGColorSpaceRelease(colorSpace);
//    
//    /*We display the result on the custom layer. All the display stuff must be done in the main thread because
//  UIKit is no thread safe, and as we are not in the main thread (remember we didn't use the main_queue)
//  we use performSelectorOnMainThread to call our CALayer and tell it to display the CGImage.*/
// [self.customLayer performSelectorOnMainThread:@selector(setContents:) withObject: (id) newImage waitUntilDone:YES];
// 
// /*We display the result on the image view (We need to change the orientation of the image so that the video is displayed correctly).
//  Same thing as for the CALayer we are not in the main thread so ...*/
// UIImage *image= [UIImage imageWithCGImage:newImage scale:1.0 orientation:UIImageOrientationRight];
// 
// /*We relase the CGImageRef*/
// CGImageRelease(newImage);
// 
// [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
// 
// /*We unlock the  image buffer*/
// CVPixelBufferUnlockBaseAddress(imageBuffer,0);
// 
// [pool drain];
}
@end

杨航收集技术资料,分享给大家



Xcode中捕获iphone/ipad/ipod手机摄像头的实时视频数据相关推荐

  1. 如何在XCode中更改iPhone或iPad模拟器类型

    如何在XCode中更改iPhone或iPad模拟器类型 参考方法一(永久,一旦设置后,每次运行指定的模拟器):(1)选择顶层菜单Project 中的 Set Active Executable(2)根 ...

  2. ipad原始邮箱服务器端口,如何在iPhone/iPad/iPod touch邮件应用程序中创建帐户(默认POP3)?...

    下面向大家介绍如何使用iPhone/iPad/iPod touch上的邮件应用程序Mail创建 yeah 邮箱帐户,这里以iPod touch为例(iPhone/iPad中除了界面略有区别外,操作基本 ...

  3. iPhone/iPad/iPod Touch各设备参数对比

    iPhone/iPad/iPod Touch各设备参数对比 xls文件:http://download.csdn.net/detail/u012881779/9173179 iPhone各设备参数比较 ...

  4. 使用 MP4box 给MP4视频嵌入字幕(特别支持iphone/ipad/ipod)

    使用 MP4box 给MP4视频嵌入字幕(特别支持iphone/ipad/ipod) 发表于  2011/12/25  由 admin Mp4box 是一款多媒体打包工具.可以操作 AVI.MPG.T ...

  5. 【转】Save SHSH Blobs for iPhone, iPad, iPod Touch with TinyUmbrella

    Using TinyUmbrella you can save SHSH blobs for iPhone 4, 3GS, 3G, iPad and iPod Touch 3G, 2G. In thi ...

  6. 聊一聊xcode中的iphone模拟器cpu与真机cpu的区别

    简述 ARM处理器,因其功耗低和尺寸小而闻名,几乎所有的手机处理器都基于ARM,苹果当然也不例外. armv6.armv7.armv7s.arm64都是ARM处理器的指令集,所有指令集原则上都是向下兼 ...

  7. 各代iphone ipad iPod各种信息 获取设备型号等等整理

    iPhone :  https://www.theiphonewiki.com/wiki/List_of_iPhones#iPhone_X iPad :   https://www.theiphone ...

  8. iPad能不能装c语言的编译器,IPhone/IPad/IPod安装GCC的方法

    GCC是一种很常用的C语言的编译器,可以在各种版本的Windows,Linux,Mac上运行,当然IPhone的IOS系统也不例外~下面就教大家如何在IPhone上面安装GCC,帮助程序猿们实现随时随 ...

  9. iPhone/iPad/iPod touch编程时版本区分

    写程序时,可能需要对应各种不同的iPhone iOS的不同,型号的不同,区分代码如下: 可以从 UIDevice 的属性 model 得到在现在执行的环境.例子如下: NSString *modeln ...

最新文章

  1. tpopela/vips_java
  2. JZOJ 4058. 【JSOI2015】子集选取
  3. webbrowser 修改浏览器版本的方法
  4. 为什么jdk的CLASSPATH环境变量需要设置rt.jar 和 tools.jar
  5. transform限制position:fixed的跟随效果
  6. C#中的扩展方法,Linq,IO和多线程的定义和实例
  7. 一个华为设备防病毒 ACL 配置
  8. android实现控件的手势缩放、移动以及双击还原
  9. 高校计算机成绩管理系统开题报告,高校科研管理系统_高校科研管理系统开题报告...
  10. WIN7 Activation
  11. AdventureWorksCycle案例分析
  12. docker删除容器
  13. android拷机工具,Android8.0平台Camera monkey拷机卡死异常解决方案
  14. 鸿蒙系统桌面搭配,华为平板 MatePad Pro 来了!首搭鸿蒙系统,与电脑“花样”协同…...
  15. 前端编写bat批处理文件,实现项目启动功能
  16. 抓包工具--Fiddler
  17. 评职称计算机应用能力考核有分吗,苏州评工程师所要求的职称计算机应用能力考核问题有哪些?...
  18. 编程15年40岁程序员的我终于在压力下被迫转行了
  19. 汇编语言实验4:分支程序题目设计
  20. 系统自学Java语言(学习视频整理)

热门文章

  1. C++中private成员变量和protect成员变量的区别
  2. 修改无效_修改劳动合同日期被认定无效,青岛一企业被判赔双倍工资
  3. Opencv——霍夫变换以及遇到的一些问题
  4. 微机原理——总线和时序
  5. AIX的完整形式是什么?
  6. Java Duration类| isNegative()方法与示例
  7. 如何在React JS组件和React JS App中添加CSS样式?
  8. a letter and a number(一封信和一个数字)
  9. c语言程序设计编程解读,【答题】C语言程序设计问题与解释实验
  10. 数据可视化【三】基本概念