Switch front/back camera with AVCaptureSession

前端 未结 5 442
时光取名叫无心
时光取名叫无心 2020-12-29 10:01

I\'m following the only answer this has on SO -

Switch cameras with avcapturesession

However cameraWithPosition does not seem to work. Deprecated?

         


        
5条回答
  •  醉梦人生
    2020-12-29 10:08

    Here is an example for using the switch with a video session:

    .h
    
    UIViewController
    
    @property(nonatomic,strong)  AVCaptureSession *CaptureSession;
    @property(nonatomic,strong) AVCaptureMovieFileOutput *MovieFileOutput;
    @property(nonatomic,strong) AVCaptureDeviceInput *VideoInputDevice;
    
    - (void) CameraSetOutputProperties;
    - (AVCaptureDevice *) CameraWithPosition:(AVCaptureDevicePosition) Position;
    

    Then:

    .m
    
    - (void)viewDidLoad {
    
       [super viewDidLoad];
    
       CaptureSession = [[AVCaptureSession alloc] init];
    
       //etc
    
    
    }
    
    - (IBAction)CameraToggle:(id)sender
    {
        if ([[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count] > 1)        //Only do if device has multiple cameras
        {
            NSError *error;
            //AVCaptureDeviceInput *videoInput = [self videoInput];
            AVCaptureDeviceInput *NewVideoInput;
            AVCaptureDevicePosition position = [[VideoInputDevice device] position];
            if (position == AVCaptureDevicePositionBack)
            {
                NewVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self CameraWithPosition:AVCaptureDevicePositionFront] error:&error];
            }
            else if (position == AVCaptureDevicePositionFront)
            {
                NewVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self CameraWithPosition:AVCaptureDevicePositionBack] error:&error];
            }
    
            if (NewVideoInput != nil)
            {
                [CaptureSession beginConfiguration];
                [CaptureSession removeInput:VideoInputDevice];
                if ([CaptureSession canAddInput:NewVideoInput])
                {
                    [CaptureSession addInput:NewVideoInput];
                    VideoInputDevice = NewVideoInput;
                }
                else
                {
                    [CaptureSession addInput:VideoInputDevice];
                }
    
                //Set the connection properties again
                [self CameraSetOutputProperties];
    
    
                [CaptureSession commitConfiguration];
            }
        }
    }
    

提交回复
热议问题