iOS 自定義相機(jī) 拍照+視頻錄制(一)



BSFramework 組件包:


shortshoot.gif

框架:<AVFoundation/AVFoundation.h>

大致流程:

  • session 初始化
  • device 初始化
  • input耍目,output 初始化,并關(guān)聯(lián)device
  • session 添加 input 和 output
  • 初始化預(yù)覽層 AVCaptureVideoPreviewLayer
  • session startRunning
  • 點(diǎn)擊拍照, didFinishProcessingPhotoSampleBuffer 代理回調(diào)后徐绑,處理數(shù)據(jù)邪驮,生成照片

PS : 其中還含有一些攝像頭翻轉(zhuǎn),閃光燈等操作傲茄,但屬于額外功能毅访,不算流程,具體全部功能看源碼


一盘榨、使用 AVCaptureSession 進(jìn)行拍照



需要的屬性大致有

@property (nonatomic ,strong) AVCaptureSession *session;
@property (nonatomic ,strong) AVCaptureDevice *device;
@property (nonatomic ,strong) AVCaptureDeviceInput *deviceInput;//圖像輸入源
@property (nonatomic ,strong) AVCaptureOutput *outPut;          //圖像輸出源
@property (nonatomic ,strong) AVPlayer *player;
@property (nonatomic ,strong) AVPlayerLayer *playerLayer;
@property (nonatomic ,strong) AVCaptureConnection *connection;



首先處理權(quán)限問題

#pragma mark - 相機(jī)授權(quán)
-(void)authorization{
    //請求相機(jī)權(quán)限
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (status == AVAuthorizationStatusNotDetermined) {
        
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                        
            dispatch_async(dispatch_get_main_queue(), ^{
                if (granted) {
                    [self authorization];
                }else{
                    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"" message:@"相機(jī)權(quán)限未開啟,請前往 手機(jī)-設(shè)置 開啟相機(jī)權(quán)限" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        
                        [self.navigationController popViewControllerAnimated:YES];
                        [self dismissViewControllerAnimated:YES completion:nil];
                    }];
                    
                    [controller addAction:action];
                    [self presentViewController:controller animated:YES completion:nil];
                    return;
                }
            });
        }];
        
    }else if (status == AVAuthorizationStatusDenied) {
        
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"" message:@"相機(jī)權(quán)限未開啟,請前往 手機(jī)-設(shè)置 開啟相機(jī)權(quán)限" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self.navigationController popViewControllerAnimated:YES];
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        
        [controller addAction:action];
        [self presentViewController:controller animated:YES completion:nil];
        
        return;
    }else if (status == AVAuthorizationStatusAuthorized){
        [self configData];
        [self initSubViews];
        [self masonryLayout];
    }
}

只有權(quán)限通過了喻粹,我才初始化 UI 界面,否則就 alert 提示草巡。

然后初始化 session 守呜,添加 device 、input山憨、output

-(void)configData{
    
    self.session = [[AVCaptureSession alloc]init];
    if ([self.session canSetSessionPreset:AVCaptureSessionPresetHigh]){
        self.session.sessionPreset = AVCaptureSessionPresetHigh;
    }else if ([self.session canSetSessionPreset:AVCaptureSessionPresetiFrame960x540]) {
        self.session.sessionPreset = AVCaptureSessionPresetiFrame960x540;
    }

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //如果不放在子線程里查乒,跳轉(zhuǎn)到相機(jī)的時候,會卡
        [self addPicIO];
        [self addVideoIO];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
            self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
            self.previewLayer.frame = CGRectMake(0, 30, SCREEN_WIDTH, SCREEN_HEIGHT - 30 - 150);
            [self.view.layer insertSublayer:self.previewLayer atIndex:0];
            [self.session startRunning];
        });
    });
}

#pragma mark 設(shè)置 拍照類型的輸入輸出源
-(void)addPicIO{
    NSError *error = nil;

    self.deviceInput = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:&error];

    if (!error) {

        if ([self.session canAddInput:self.deviceInput]) {
            [self.session addInput:self.deviceInput];
        }

        if ([self.session canAddOutput:self.outPut]) {
            [self.session addOutput:self.outPut];
        }
    }
}


點(diǎn)擊拍照處理

#pragma mark - action 交互事件

// 拍照
-(void)takePicture{
    
    // 防止快速連點(diǎn)
    if (self.bottomView.recordStatus == RECORD_STATUS_UNRECORD) {
        return;
    }

    if (@available(iOS 10.0, *)) {

        AVCapturePhotoOutput *outPut = (AVCapturePhotoOutput *)self.outPut;

        AVCapturePhotoSettings *settings = [AVCapturePhotoSettings photoSettingsWithFormat:@{AVVideoCodecKey:AVVideoCodecJPEG}];
        [outPut capturePhotoWithSettings:settings delegate:self];
   
    }else{
        
        // 兼容iOS 10以下機(jī)型郁竟,未測試玛迄,不清楚可不可以用
        self.connection = [self.outPut connectionWithMediaType:AVMediaTypeVideo];
        [self.connection setVideoOrientation:AVCaptureVideoOrientationPortrait];

        AVCaptureStillImageOutput *outPut = (AVCaptureStillImageOutput *)self.outPut;

        [outPut captureStillImageAsynchronouslyFromConnection:self.connection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {

            [self.session stopRunning];
            
            NSData *jpegData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:jpegData];
            self.photoImageView.image = image;
            self.photoImageView.hidden = NO;
        }];
    }

    if ([self.delegate respondsToSelector:@selector(photoCameraTakeBtnClicked)]) {
        [self.delegate photoCameraTakeBtnClicked];
    }
}

代理回調(diào)處理

-(void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhotoSampleBuffer:(CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(AVCaptureBracketedStillImageSettings *)bracketSettings error:(NSError *)error API_AVAILABLE(ios(10.0)){

    if (photoSampleBuffer) {
        [self.session stopRunning];
        NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
        UIImage *image = [UIImage imageWithData:data];
        self.photoImageView.image = image;
        self.photoImageView.hidden = NO;
    }
}

PS : 此代理是 iOS 10 以后的方法,低于 iOS 10 需要使用 ↓↓↓

// 兼容iOS 10以下機(jī)型棚亩,未測試蓖议,不清楚可不可以用
    self.connection = [self.outPut connectionWithMediaType:AVMediaTypeVideo];
    [self.connection setVideoOrientation:AVCaptureVideoOrientationPortrait];

    AVCaptureStillImageOutput *outPut = (AVCaptureStillImageOutput *)self.outPut;

    [outPut captureStillImageAsynchronouslyFromConnection:self.connection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {

        [self.session stopRunning];
            
        NSData *jpegData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [UIImage imageWithData:jpegData];
        self.photoImageView.image = image;
        self.photoImageView.hidden = NO;
    }];

友情鏈接


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市蔑舞,隨后出現(xiàn)的幾起案子拒担,更是在濱河造成了極大的恐慌,老刑警劉巖攻询,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件从撼,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)低零,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門婆翔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人掏婶,你說我怎么就攤上這事啃奴。” “怎么了雄妥?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵最蕾,是天一觀的道長。 經(jīng)常有香客問我老厌,道長瘟则,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任枝秤,我火速辦了婚禮醋拧,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘淀弹。我一直安慰自己丹壕,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布薇溃。 她就那樣靜靜地躺著菌赖,像睡著了一般。 火紅的嫁衣襯著肌膚如雪痊焊。 梳的紋絲不亂的頭發(fā)上盏袄,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天,我揣著相機(jī)與錄音薄啥,去河邊找鬼辕羽。 笑死,一個胖子當(dāng)著我的面吹牛垄惧,可吹牛的內(nèi)容都是我干的刁愿。 我是一名探鬼主播,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼到逊,長吁一口氣:“原來是場噩夢啊……” “哼铣口!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起觉壶,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤脑题,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后铜靶,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體叔遂,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了已艰。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片痊末。...
    茶點(diǎn)故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖哩掺,靈堂內(nèi)的尸體忽然破棺而出凿叠,到底是詐尸還是另有隱情,我是刑警寧澤嚼吞,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布盒件,位于F島的核電站,受9級特大地震影響誊薄,放射性物質(zhì)發(fā)生泄漏履恩。R本人自食惡果不足惜锰茉,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一呢蔫、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧飒筑,春花似錦片吊、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至肤晓,卻和暖如春爷贫,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背补憾。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工漫萄, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人盈匾。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓腾务,卻偏偏與公主長得像,于是被迫代替她去往敵國和親削饵。 傳聞我的和親對象是個殘疾皇子岩瘦,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評論 2 354