UIKit-AVCapture(创建一个简单的摄像头demo)

AVCaptureVideoPreviewLayer

用于显示摄像头采集到的实时视频预览,可以直接添加到视图层次结构中。
AVCaptureVideoPreviewLayer可以嵌入

AVCaptureSession

处理摄像头捕获的数据封装后给屏幕

AVCaptureConnection

用于管理捕获会话中的数据流连接,包括视频、音频和元数据的连接。通过这个连接,你可以设置或查询与视频预览相关的属性,例如视频方向、视频镜像等。

最简单的demo

main.m

//
//  main.m
//  cameraTest
//
//  Created by Renkai Yang on 12/8/23.
//

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "ViewController.h"
int main(int argc, char * argv[]) {
    NSString * appDelegateClassName;
    @autoreleasepool {
        // Setup code that might create autoreleased objects goes here.
        appDelegateClassName = NSStringFromClass([AppDelegate class]);
                CameraViewController *cameraViewController = [[CameraViewController alloc] init];
                [cameraViewController viewDidLoad];
//                [[NSRunLoop currentRunLoop] run];
    }
    return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}

viewController.m

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

@interface CameraViewController : UIViewController

@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;


@end

@implementation CameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 创建 AVCaptureSession
    self.captureSession = [[AVCaptureSession alloc] init];

    // 设置摄像头为后置摄像头
    AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (videoDevice) {
        NSError *error;
        AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
        if (!error) {
            [self.captureSession addInput:videoInput];
        } else {
            NSLog(@"Error setting up video input: %@", error);
        }
    } else {
        NSLog(@"Video device not available");
    }

    // 创建 AVCaptureVideoPreviewLayer
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.previewLayer.frame = self.view.layer.bounds;
    [self.view.layer addSublayer:self.previewLayer];
    
//    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
//    for (AVCaptureDevice *device in devices) {
//        NSLog(@"Device name: %@", [device localizedName]);
//        NSLog(@"Device position: %ld", (long)[device position]);
//    }

    // 启动 AVCaptureSession
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self.captureSession startRunning];
        });
}

@end

ViewController.h

#import <UIKit/UIKit.h>

@interface CameraViewController : UIViewController


@end

在这里插入图片描述
info.plist
在这里插入图片描述

你可能感兴趣的:(UIKit,ios)