您的位置:首页 > 移动开发 > IOS开发

iOS编程--AVCapture编程理解--自定义相机

2016-04-14 12:06 387 查看

AVCapture编程理解(自定义相机)

媒体采集的几个东西。这里所需要明白的是,在这个流程中,这里会存在几个对象:

a、AVCaptureDevice。这里代表抽象的硬件设备。
b、AVCaptureInput。这里代表输入设备(可以是它的子类),它配置抽象硬件设备的ports。
c、AVCaptureOutput。它代表输出数据,管理着输出到一个movie或者图像。
d、AVCaptureSession。它是input和output的桥梁。它协调着intput到output的数据传输。


1、高层面关系:

有很多Device的input,也有很多数据类型的Output,都通过一个Capture Session来控制进行传输。
也即:CaptureDevice适配AVCaptureInput,通过Session来输入到AVCaptureOutput中。
这样也就达到了从设备到文件等持久化传输的目的(如从相机设备采集图像到UIImage中)。
特别注意,这里的关系是可以通过唯一一个Capture Session来同时控制设备的输入和输出。

那么存在一个问题了:视频输入(input)就对应视频的输出(output),而音频输入就应对应音频的输出,
因而需要建立对应的Connections,来各自连接它们。我们的AVCaptureOutput可以获取到相应的数据。
一个ACCaptureConnection可以控制input到output的数据传输。


2、Session及其使用模式

You use an instance to coordinate the flow of data from AV input devices to outputs.
You add the capture devices and outputs you want to the session,
then start data flow by sending the session a startRunning message,
and stop recording by sending a stopRunning message.


AVCaptureSession *session = [[AVCaptureSession alloc] init];
//Add inputs and outputs.
[session startRunning];


这里表明了,需要create一个session,然后发running消息给它,它会自动跑起来,
删除旧的device等一系列操作,那么就需要使用如下方法:


[session beginConfiguration];
// Remove an existing capture device.
// Add a new capture device.
// Reset the preset.
[session commitConfiguration];


来进行处理。
当然,如果session的时候发生了异常,那么我们可以通过notification去observe相关的事件
(可以在AVCaptureSession Class Reference中的Nofications中找到相应的情况),
而session如果出现相应问题时,它会post出来,此时我们就可以处理了。


3、谈谈AVCaptureDevice

InputDevice即是对硬件的抽象,一对一的。一个AVCaptureDevice对象,对应一个实际的硬件设备。
那么显然,我们可以通过AVCaptureDevice的类方法devices或devicesWithMediaType去获取全部或局部设备列表。
(当然也可以检测相应的设备是否可以使用,这里注意有设备抢占问题,当前是否可用)


if([currentDeviceisFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus])


此外,设置对焦点CGPoint时,需要注意位置:

a CGPoint where {0,0} represents the top left of the picture area,
and {1,1} represents the bottom right in landscape mode with the home button on the right。

当我们需要对一个设备的属性进行观察,我们可以使用KVO来处理。
(为啥观察,比如我们需要知道设备此时是否正在对焦or已经停止了对焦)
对于一个device的属性更改,我们的做法通常是:


if([deviceisFocusModeSupported:AVCaptureFocusModeLocked])
//do configuring
[device unlockForConfiguration];
}
else{//Respond to the failure as appropriate.


4、CaptureInput的构建和添加到Session中的方法

/*创建并配置输入设备*/
AVCaptureDevice *device =
[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *input =
[AVCaptureDeviceInput deviceInputWithDevice:device error:&error];

//添加input到session的模式是(检查可否添加到session,然后根据情况添加或者不添加):
AVCaptureSession *captureSession = <#Get a capture session#>;
if ([captureSession canAddInput:input]) {
[captureSession addInput:captureDeviceInput];
}
else{//handle the failure.}


5、output的分类和使用

在ios中,分为MovieFile、VideoData、AudioData和StillImage几种output,使用方式类似,只是范围不同。
另外,它们都继承于AVCaptureOutput。
第一个是输出成movie文件,第二个适用于逐个Frame的处理,第三个适用于声音采集,第四个是still image(静态图像<拍照>)相关。
他们的添加方式都是使用session的addOutput方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: