文章目录
一、自定义相机的封装(AVFoundation)
如何使用AVFoundation来实现一个相机预览功能请移步:iOS开发(自定义相机的实现)——AVFoundation的基本使用
问题重现:在之前写的相机功能中,如果多个页面需要实现相机,那代码的重复率会特别高,这个无疑是个严重的弊端,因此这里重新封装一下相机,以实现代码的简洁性。
1. 创建videoCaptureManager类,继承自NSObject
2. 在.h文件中,实现一个自定义的协议Protocol和代理。
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@protocol CaptureDataOutputProtocol;
@interface videoCaptureManager : NSObject
@property (nonatomic, readwrite, weak) id<CaptureDataOutputProtocol> delegate;
@property (nonatomic, readwrite, assign) BOOL runningStatus;
/**
* 设定使用前置摄像头或者后置摄像头
* AVCaptureDevicePositionFront 前置摄像头(默认)
* AVCaptureDevicePositionBack 后置摄像头
*/
@property (nonatomic, readwrite, assign) AVCaptureDevicePosition position;
- (void)startSession;
- (void)stopSession;
- (void)resetSession;
- (AVCaptureSession *)returnSession;
@end
@protocol CaptureDataOutputProtocol <NSObject>
/**
* 回调每一个分帧的image
*/
- (void)captureOutputImage:(UIImage *)image;
- (void)captureOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer;
- (void)captureError;
@end
3. 在.m文件中实现相应的功能
#import "videoCaptureManager.h"
@interface videoCaptureManager() <AVCaptureVideoDataOutputSampleBufferDelegate>{
dispatch_queue_t _queue;
}
@property (nonatomic, readwrite, retain) AVCaptureSession *session;
@property (nonatomic, readwrite, retain) AVCaptureDevice *captureDevice;
@property (nonatomic, readwrite, retain) AVCaptureDeviceInput *input;
@property (nonatomic, readwrite, retain) AVCaptureVideoDataOutput *output;
@property (nonatomic, readwrite, assign) BOOL isSessionBegin;
@end
@implementation videoCaptureManager
- (void)setPosition:(AVCaptureDevicePosition)position {
if (_position ^ position) {
_position = position;
if (self.isSessionBegin) {
[self resetSession];
}
}
}
- (instancetype)init {
if (self = [super init]) {
_session = [[AVCaptureSession alloc] init];
_session.sessionPreset = AVCaptureSessionPreset640x480;
_queue = dispatch_queue