- 图片视频捕捉功能
AVFoundation
- 捕捉会话:AVCaptureSession
- 捕捉设备:AVCaptureDevice
- 捕捉设备输入:AVCaptureDeviceInput
- 捕捉设备输出:AVCaptureOutput抽象类
AVCaptureStillImageOutput
AVCaputureMovieFileOutput
AVCaputureAudioDataOutput
AVCaputureVideoDataOutput - 捕捉连接:AVCaptureConnection
- 捕捉预览:AVCaptureVideoPreviewLayer
用法实例:
目的:视频/照片的捕捉
- 设置session
初始化
配置分配率
配置输入设备(注意转换为AVCaptureDeviceInput)
配置输入设备包括音频输入,视频输入
配置输出(静态图片输出,视频文件输出)
在为session添加输入输出时,注意一定判断是否能添加:原因是:摄像头并不隶属于任何一个APP,它是公共设备。
实例代码
- (BOOL)setupSession:(NSError **)error {
//创建捕捉会话。AVCaptureSession 是捕捉场景的中心枢纽
self.captureSession = [[AVCaptureSession alloc]init];
/*
AVCaptureSessionPresetHigh
AVCaptureSessionPresetMedium
AVCaptureSessionPresetLow
AVCaptureSessionPreset640x480
AVCaptureSessionPreset1280x720
AVCaptureSessionPresetPhoto
*/
//设置图像的分辨率
self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
//拿到默认视频捕捉设备 iOS系统返回后置摄像头
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//将捕捉设备封装成AVCaptureDeviceInput
//注意:为会话添加捕捉设备,必须将设备封装成AVCaptureDeviceInput对象
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:error];
//判断videoInput是否有效
if (videoInput){
//canAddInput:测试是否能被添加到会话中
if ([self.captureSession canAddInput:videoInput]){
//将videoInput 添加到 captureSession中
[self.captureSession addInput:videoInput];
self.activeVideoInput = videoInput;
}
}else{
return NO;
}
//选择默认音频捕捉设备 即返回一个内置麦克风
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
//为这个设备创建一个捕捉设备输入
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:error];
//判断audioInput是否有效
if (audioInput) {
//canAddInput:测试是否能被添加到会话中
if ([self.captureSession canAddInput:audioInput])
{
//将audioInput 添加到 captureSession中
[self.captureSession addInput:audioInput];
}
}else
{
return NO;
}
//AVCaptureStillImageOutput 实例 从摄像头捕捉静态图片
self.imageOutput = [[AVCapturePhotoOutput alloc]init];
//配置字典:希望捕捉到JPEG格式的图片
// self.imageOutput.outputSettings = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
//输出连接 判断是否可用,可用则添加到输出连接中去
if ([self.captureSession canAddOutput:self.imageOutput])
{
[self.captureSession addOutput:self.imageOutput];
}
//创建一个AVCaptureMovieFileOutput 实例,用于将Quick Time 电影录制到文件系统
self.movieOutput = [[AVCaptureMovieFileOutput alloc]init];
//输出连接 判断是否可用,可用则添加到输出连接中去
if ([self.captureSession canAddOutput:self.movieOutput])
{
[self.captureSession addOutput:self.movieOutput];
}
return YES;
}
如此捕捉已经完成,接下来看预览
捕捉预览
1)在UIView 重写layerClass 类方法可以让开发者创建视图实例自定义图层了下
重写layerClass方法并返回AVCaptureVideoPrevieLayer类对象
@interface THPreviewView : UIView
//session用来关联AVCaptureVideoPreviewLayer 和 激活AVCaptureSession
@property (strong, nonatomic) AVCaptureSession *session;
@end
@implementation THPreviewView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setupView];
}
return self;
}
- (void)setupView {
[(AVCaptureVideoPreviewLayer *)self.layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
}
+ (Class)layerClass {
//在UIView 重写layerClass 类方法可以让开发者创建视图实例自定义图层了下
//重写layerClass方法并返回AVCaptureVideoPrevieLayer类对象
return [AVCaptureVideoPreviewLayer class];
}
- (AVCaptureSession*)session {
//重写session方法,返回捕捉会话
return [(AVCaptureVideoPreviewLayer*)self.layer session];
}
- (void)setSession:(AVCaptureSession *)session {
//重写session属性的访问方法,在setSession:方法中访问视图layer属性。
//AVCaptureVideoPreviewLayer 实例,并且设置AVCaptureSession 将捕捉数据直接输出到图层中,并确保与会话状态同步。
[(AVCaptureVideoPreviewLayer*)self.layer setSession:session];
}
捕捉预览
如此就完成了捕捉及预览了
@implementation ViewController
[self setupSession: nil];
self.previewView = [THPreviewView new];
self.previewView.frame = self.view.bounds;
self.previewView.session = self.captureSession;
[self.view addSubview:self.previewView];
[self.captureSession startRunning];
其他功能
调换摄像头
//切换摄像头
- (BOOL)switchCameras {
//判断是否有多个摄像头
if (![self canSwitchCameras]){
return NO;
}
//获取当前设备的反向设备
NSError *error;
AVCaptureDevice *videoDevice = [self inactiveCamera];
//将输入设备封装成AVCaptureDeviceInput
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
//判断videoInput 是否为nil
if (videoInput){
//标注原配置变化开始
[self.captureSession beginConfiguration];
//将捕捉会话中,原本的捕捉输入设备移除
[self.captureSession removeInput:self.activeVideoInput];
//判断新的设备是否能加入
if ([self.captureSession canAddInput:videoInput]){
//能加入成功,则将videoInput 作为新的视频捕捉设备
[self.captureSession addInput:videoInput];
//将获得设备 改为 videoInput
self.activeVideoInput = videoInput;
}else{
//如果新设备,无法加入。则将原本的视频捕捉设备重新加入到捕捉会话中
[self.captureSession addInput:self.activeVideoInput];
}
//配置完成后, AVCaptureSession commitConfiguration 会分批的将所有变更整合在一起。
[self.captureSession commitConfiguration];
} else{
//创建AVCaptureDeviceInput 出现错误,则通知委托来处理该错误
// [self.delegate deviceConfigurationFailedWithError:error];
return NO;
}
return YES;
}
//判断是否有超过1个摄像头可用
- (BOOL)canSwitchCameras {
return self.cameraCount > 1;
}
//可用视频捕捉设备的数量
- (NSUInteger)cameraCount {
return [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
}
- (AVCaptureDevice *)activeCamera {
//返回当前捕捉会话对应的摄像头的device 属性
return self.activeVideoInput.device;
}
//返回当前未激活的摄像头
- (AVCaptureDevice *)inactiveCamera {
//通过查找当前激活摄像头的反向摄像头获得,如果设备只有1个摄像头,则返回nil
AVCaptureDevice *device = nil;
if (self.cameraCount > 1){
if ([self activeCamera].position == AVCaptureDevicePositionBack) {
device = [self cameraWithPosition:AVCaptureDevicePositionFront];
}else{
device = [self cameraWithPosition:AVCaptureDevicePositionBack];
}
}
return device;
}
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position {
//获取可用视频设备
NSArray *devicess = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
//遍历可用的视频设备 并返回position 参数值
for (AVCaptureDevice *device in devicess){
if (device.position == position) {
return device;
}
}
return nil;
}
然后调用 switchCameras就能调换摄像头了
摄像头聚焦
- (void)focusAtPoint:(CGPoint)point {
AVCaptureDevice *device = [self activeCamera];
//是否支持兴趣点对焦 & 是否自动对焦模式
if (device.isFocusPointOfInterestSupported && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
NSError *error;
//锁定设备准备配置,如果获得了锁
if ([device lockForConfiguration:&error]) {
//将focusPointOfInterest属性设置CGPoint
device.focusPointOfInterest = point;
//focusMode 设置为AVCaptureFocusModeAutoFocus
device.focusMode = AVCaptureFocusModeAutoFocus;
//释放该锁定
[device unlockForConfiguration];
}else{
//错误时,则返回给错误处理代理
}
}
}
曝光
static const NSString *THCameraAdjustingExposureContext;
- (void)exposeAtPoint:(CGPoint)point {
AVCaptureDevice *device = [self activeCamera];
AVCaptureExposureMode exposureMode =AVCaptureExposureModeContinuousAutoExposure;
//判断是否支持 AVCaptureExposureModeContinuousAutoExposure 模式
if (device.isExposurePointOfInterestSupported && [device isExposureModeSupported:exposureMode]) {
[device isExposureModeSupported:exposureMode];
NSError *error;
//锁定设备准备配置
if ([device lockForConfiguration:&error]) {
//配置期望值
device.exposurePointOfInterest = point;
device.exposureMode = exposureMode;
//判断设备是否支持锁定曝光的模式。
if ([device isExposureModeSupported:AVCaptureExposureModeLocked]) {
//支持,则使用kvo确定设备的adjustingExposure属性的状态。
[device addObserver:self forKeyPath:@"adjustingExposure" options:NSKeyValueObservingOptionNew context:&THCameraAdjustingExposureContext];
}
//释放该锁定
[device unlockForConfiguration];
}else{
///错误处理
}
}
}
拍摄静态图片
#pragma mark - Image Capture Methods 拍摄静态图片
/*
AVCaptureStillImageOutput 是AVCaptureOutput的子类。用于捕捉图片
*/
- (void)captureStillImage {
//获取连接
AVCaptureConnection *connection = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
//程序只支持纵向,但是如果用户横向拍照时,需要调整结果照片的方向
//判断是否支持设置视频方向
if (connection.isVideoOrientationSupported) {
//获取方向值
connection.videoOrientation = [self currentVideoOrientation];
}
//定义一个handler 块,会返回1个图片的NSData数据
id handler = ^(CMSampleBufferRef sampleBuffer,NSError *error){
if (sampleBuffer != NULL) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:sampleBuffer];
UIImage *image = [[UIImage alloc]initWithData:imageData];
//重点:捕捉图片成功后,将图片传递出去
[self writeImageToAssetsLibrary:image];
}else{
NSLog(@"NULL sampleBuffer:%@",[error localizedDescription]);
}
};
//捕捉静态图片
[self.imageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:handler];
}
/*
Assets Library 框架
用来让开发者通过代码方式访问iOS photo
注意:会访问到相册,需要修改plist 权限。否则会导致项目崩溃
*/
- (void)writeImageToAssetsLibrary:(UIImage *)image {
//创建ALAssetsLibrary 实例
ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
//参数1:图片(参数为CGImageRef 所以image.CGImage)
//参数2:方向参数 转为NSUInteger
//参数3:写入成功、失败处理
[library writeImageToSavedPhotosAlbum:image.CGImage
orientation:(NSUInteger)image.imageOrientation
completionBlock:^(NSURL *assetURL, NSError *error) {
}];
}
//获取方向值
- (AVCaptureVideoOrientation)currentVideoOrientation {
AVCaptureVideoOrientation orientation;
//获取UIDevice 的 orientation
switch ([UIDevice currentDevice].orientation) {
case UIDeviceOrientationPortrait:
orientation = AVCaptureVideoOrientationPortrait;
break;
case UIDeviceOrientationLandscapeRight:
orientation = AVCaptureVideoOrientationLandscapeLeft;
break;
case UIDeviceOrientationPortraitUpsideDown:
orientation = AVCaptureVideoOrientationPortraitUpsideDown;
break;
default:
orientation = AVCaptureVideoOrientationLandscapeRight;
break;
}
return orientation;
}
捕捉视频
#pragma mark - Video Capture Methods 捕捉视频
//判断是否录制状态
- (BOOL)isRecording {
return self.movieOutput.isRecording;
}
//开始录制
- (void)startRecording {
if (![self isRecording]) {
//获取当前视频捕捉连接信息,用于捕捉视频数据配置一些核心属性
AVCaptureConnection * videoConnection = [self.movieOutput connectionWithMediaType:AVMediaTypeVideo];
//判断是否支持设置videoOrientation 属性。
if([videoConnection isVideoOrientationSupported]){
//支持则修改当前视频的方向
videoConnection.videoOrientation = [self currentVideoOrientation];
}
//判断是否支持视频稳定 可以显著提高视频的质量。只会在录制视频文件涉及
if([videoConnection isVideoStabilizationSupported]){
videoConnection.enablesVideoStabilizationWhenAvailable = YES;
}
AVCaptureDevice *device = [self activeCamera];
//摄像头可以进行平滑对焦模式操作。即减慢摄像头镜头对焦速度。当用户移动拍摄时摄像头会尝试快速自动对焦。
if (device.isSmoothAutoFocusEnabled) {
NSError *error;
if ([device lockForConfiguration:&error]) {
device.smoothAutoFocusEnabled = YES;
[device unlockForConfiguration];
} else {
/// 错误处理
// [self.delegate deviceConfigurationFailedWithError:error];
}
}
//查找写入捕捉视频的唯一文件系统URL.
self.outputURL = [self uniqueURL];
//在捕捉输出上调用方法 参数1:录制保存路径 参数2:代理
[self.movieOutput startRecordingToOutputFileURL:self.outputURL recordingDelegate:self];
}
}
//停止录制
- (void)stopRecording {
//是否正在录制
if ([self isRecording]) {
[self.movieOutput stopRecording];
}
}
//写入视频唯一文件系统URL
- (NSURL *)uniqueURL {
NSFileManager *fileManager = [NSFileManager defaultManager];
//temporaryDirectoryWithTemplateString 可以将文件写入的目的创建一个唯一命名的目录;
NSString *dirPath = [fileManager temporaryDirectoryWithTemplateString:@"kamera.XXXXXX"];
if (dirPath) {
NSString *filePath = [dirPath stringByAppendingPathComponent:@"kamera_movie.mov"];
return [NSURL fileURLWithPath:filePath];
}
return nil;
}
#pragma mark - AVCaptureFileOutputRecordingDelegate
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error {
//错误
if (error) {
// [self.delegate mediaCaptureFailedWithError:error];
}else{
//写入
[self writeVideoToAssetsLibrary:[self.outputURL copy]];
}
self.outputURL = nil;
}
//写入捕捉到的视频
- (void)writeVideoToAssetsLibrary:(NSURL *)videoURL {
//ALAssetsLibrary 实例 提供写入视频的接口
ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
//写资源库写入前,检查视频是否可被写入 (写入前尽量养成判断的习惯)
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:videoURL]) {
//创建block块
ALAssetsLibraryWriteVideoCompletionBlock completionBlock;
completionBlock = ^(NSURL *assetURL,NSError *error){
if (error) {
// [self.delegate assetLibraryWriteFailedWithError:error];
}else{
//用于界面展示视频缩略图
// [self generateThumbnailForVideoAtURL:videoURL];
}
};
//执行实际写入资源库的动作
[library writeVideoAtPathToSavedPhotosAlbum:videoURL completionBlock:completionBlock];
}
}
demo
kwwh