UFO ET IT

avcapturesession으로 카메라 전환

ufoet 2021. 1. 17. 11:36
반응형

avcapturesession으로 카메라 전환


이 자습서 사용 : http://www.musicalgeometry.com/?p=1297를 사용 하여 사용자 지정 오버레이 및 이미지 캡처를 만들었습니다 AVCaptureSession.

사용자가 전면 카메라와 후면 카메라를 전환 할 수 있도록하려고합니다. CaptureSessionManager카메라를 전환하는 코드는 다음과 같습니다 .

- (void)addVideoInputFrontCamera:(BOOL)front {
    NSArray *devices = [AVCaptureDevice devices];
    AVCaptureDevice *frontCamera;
    AVCaptureDevice *backCamera;

    for (AVCaptureDevice *device in devices) {

        //NSLog(@"Device name: %@", [device localizedName]);

        if ([device hasMediaType:AVMediaTypeVideo]) {

            if ([device position] == AVCaptureDevicePositionBack) {
                //NSLog(@"Device position : back");
                backCamera = device;
            }
            else {
                //NSLog(@"Device position : front");
                frontCamera = device;
            }
        }
    }

    NSError *error = nil;

    if (front) {
        AVCaptureDeviceInput *frontFacingCameraDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:frontCamera error:&error];
        if (!error) {
            if ([[self captureSession] canAddInput:frontFacingCameraDeviceInput]) {
                [[self captureSession] addInput:frontFacingCameraDeviceInput];
            } else {
                NSLog(@"Couldn't add front facing video input");
            }
        }
    } else {
        AVCaptureDeviceInput *backFacingCameraDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:backCamera error:&error];
        if (!error) {
            if ([[self captureSession] canAddInput:backFacingCameraDeviceInput]) {
                [[self captureSession] addInput:backFacingCameraDeviceInput];
            } else {
                NSLog(@"Couldn't add back facing video input");
            }
        }
    }
}

이제 내 사용자 지정 오버레이 컨트롤러에서 viewDidLoad다음 과 같이 모든 것을 초기화합니다 .

[self setCaptureManager:[[CaptureSessionManager alloc] init]];

[[self captureManager] addVideoInputFrontCamera:NO]; // set to YES for Front Camera, No for Back camera

[[self captureManager] addStillImageOutput];

[[self captureManager] addVideoPreviewLayer];
CGRect layerRect = [[[self view] layer] bounds];
[[[self captureManager] previewLayer] setBounds:layerRect];
[[[self captureManager] previewLayer] setPosition:CGPointMake(CGRectGetMidX(layerRect),CGRectGetMidY(layerRect))];
[[[self view] layer] addSublayer:[[self captureManager] previewLayer]];

[[_captureManager captureSession] startRunning];

카메라 전환 버튼은라는 메서드에 연결됩니다 switchCamera. 나는 이것을 시도했다 :

- (void)switchCameraView:(id)sender {

    [[self captureManager] addVideoInputFrontCamera:YES]; // set to YES for Front Camera, No for Back camera

}

이 호출 할 때 나는 오류 얻을 NSLog로부터를 CaptureSessionManager하고 그 이유를 알아낼 수 없습니다. 에서 viewDidLoad내가 설정 한 경우 fontCameraYES, 그것은 전면 카메라를 표시하지만 다시로 전환 할 수 있고, 그 반대의 경우도 마찬가지입니다.

제대로 전환하는 방법에 대한 아이디어가 있습니까?


먼저 AVCaptureSession에서 기존 AVCameraInput을 제거한 다음 AVCaptureSession에 새 AVCameraInput을 추가해야합니다. 다음은 나를 위해 작동합니다 (ARC에서).

-(IBAction)switchCameraTapped:(id)sender
{
    //Change camera source
    if(_captureSession)
    {
        //Indicate that some changes will be made to the session
        [_captureSession beginConfiguration];

        //Remove existing input
        AVCaptureInput* currentCameraInput = [_captureSession.inputs objectAtIndex:0];
        [_captureSession removeInput:currentCameraInput];

        //Get new input
        AVCaptureDevice *newCamera = nil;
        if(((AVCaptureDeviceInput*)currentCameraInput).device.position == AVCaptureDevicePositionBack)
        {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
        }
        else
        {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
        }

        //Add input to session
        NSError *err = nil;
        AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
        if(!newVideoInput || err)
        {
            NSLog(@"Error creating capture device input: %@", err.localizedDescription);
        }
        else
        {
            [_captureSession addInput:newVideoInput];
        }

        //Commit all the configuration changes at once
        [_captureSession commitConfiguration];
    }
}

// Find a camera with the specified AVCaptureDevicePosition, returning nil if one is not found
- (AVCaptureDevice *) cameraWithPosition:(AVCaptureDevicePosition) position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) 
    {
        if ([device position] == position) return device;
    }
    return nil;
}

스위프트 4

@IBAction func switchCameraTapped(sender: Any) {
    //Change camera source
    if let session = captureSession {
        //Indicate that some changes will be made to the session
        session.beginConfiguration()

        //Remove existing input
        guard let currentCameraInput: AVCaptureInput = session.inputs.first else {
            return
        }

        session.removeInput(currentCameraInput)

        //Get new input
        var newCamera: AVCaptureDevice! = nil
        if let input = currentCameraInput as? AVCaptureDeviceInput {
            if (input.device.position == .back) {
                newCamera = cameraWithPosition(position: .front)
            } else {
                newCamera = cameraWithPosition(position: .back)
            }
        }

        //Add input to session
        var err: NSError?
        var newVideoInput: AVCaptureDeviceInput!
        do {
            newVideoInput = try AVCaptureDeviceInput(device: newCamera)
        } catch let err1 as NSError {
            err = err1
            newVideoInput = nil
        }

        if newVideoInput == nil || err != nil {
            print("Error creating capture device input: \(err?.localizedDescription)")
        } else {
            session.addInput(newVideoInput)
        }

        //Commit all the configuration changes at once
        session.commitConfiguration()
    }
}

// Find a camera with the specified AVCaptureDevicePosition, returning nil if one is not found
func cameraWithPosition(position: AVCaptureDevice.Position) -> AVCaptureDevice? {
    let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified)
    for device in discoverySession.devices {
        if device.position == position {
            return device
        }
    }

    return nil
}

Swift 3 Edit (François-Julien Alcaraz 답변과 결합) :

@IBAction func switchCameraTapped(sender: Any) {
    //Change camera source
    if let session = captureSession {
        //Indicate that some changes will be made to the session
        session.beginConfiguration()

        //Remove existing input
        guard let currentCameraInput: AVCaptureInput = session.inputs.first as? AVCaptureInput else {
            return
        }

        session.removeInput(currentCameraInput)

        //Get new input
        var newCamera: AVCaptureDevice! = nil
        if let input = currentCameraInput as? AVCaptureDeviceInput {
            if (input.device.position == .back) {
                newCamera = cameraWithPosition(position: .front)
            } else {
                newCamera = cameraWithPosition(position: .back)
            }
        }

        //Add input to session
        var err: NSError?
        var newVideoInput: AVCaptureDeviceInput!
        do {
            newVideoInput = try AVCaptureDeviceInput(device: newCamera)
        } catch let err1 as NSError {
            err = err1
            newVideoInput = nil
        }

        if newVideoInput == nil || err != nil {
            print("Error creating capture device input: \(err?.localizedDescription)")
        } else {
            session.addInput(newVideoInput)
        }

        //Commit all the configuration changes at once
        session.commitConfiguration()
    }
}

// Find a camera with the specified AVCaptureDevicePosition, returning nil if one is not found
func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice? {
    if let discoverySession = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .unspecified) {
        for device in discoverySession.devices {
            if device.position == position {
                return device
            }
        }
    }

    return nil
}

@ NES_4Life의 답변에 대한 Swift 버전 :

@IBAction func switchCameraTapped(sender: AnyObject) {
    //Change camera source
    if let session = captureSession {
        //Indicate that some changes will be made to the session
        session.beginConfiguration()

        //Remove existing input
        let currentCameraInput:AVCaptureInput = session.inputs.first as! AVCaptureInput
        session.removeInput(currentCameraInput)

        //Get new input
        var newCamera:AVCaptureDevice! = nil
        if let input = currentCameraInput as? AVCaptureDeviceInput {
            if (input.device.position == .Back)
            {
                newCamera = cameraWithPosition(.Front)
            }
            else
            {
                newCamera = cameraWithPosition(.Back)
            }
        }

        //Add input to session
        var err: NSError?
        var newVideoInput: AVCaptureDeviceInput!
        do {
            newVideoInput = try AVCaptureDeviceInput(device: newCamera)
        } catch let err1 as NSError {
            err = err1
            newVideoInput = nil
        }

        if(newVideoInput == nil || err != nil)
        {
            print("Error creating capture device input: \(err!.localizedDescription)")
        }
        else
        {
            session.addInput(newVideoInput)
        }

        //Commit all the configuration changes at once
        session.commitConfiguration()
    }
}

// Find a camera with the specified AVCaptureDevicePosition, returning nil if one is not found
func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice?
{
    let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
    for device in devices {
        let device = device as! AVCaptureDevice
        if device.position == position {
            return device
        }
    }

    return nil
}

이전 답변을 기반으로 몇 가지 유효성 검사와 하나의 특정 변경 사항으로 자체 버전을 만들었으므로 현재 카메라 입력이 캡처 세션 입력의 첫 번째 개체가 아닐 수 있으므로 다음을 변경했습니다.

//Remove existing input
AVCaptureInput* currentCameraInput = [self.captureSession.inputs objectAtIndex:0];
[self.captureSession removeInput:currentCameraInput];

이를 위해 (모든 비디오 유형 입력 제거) :

for (AVCaptureDeviceInput *input in self.captureSession.inputs) {
    if ([input.device hasMediaType:AVMediaTypeVideo]) {
        [self.captureSession removeInput:input];
        break;
    }
}

전체 코드는 다음과 같습니다.

if (!self.captureSession) return;

[self.captureSession beginConfiguration];

AVCaptureDeviceInput *currentCameraInput;

// Remove current (video) input
for (AVCaptureDeviceInput *input in self.captureSession.inputs) {
    if ([input.device hasMediaType:AVMediaTypeVideo]) {
        [self.captureSession removeInput:input];

        currentCameraInput = input;
        break;
    }
}

if (!currentCameraInput) return;

// Switch device position
AVCaptureDevicePosition captureDevicePosition = AVCaptureDevicePositionUnspecified;
if (currentCameraInput.device.position == AVCaptureDevicePositionBack) {
    captureDevicePosition = AVCaptureDevicePositionFront;
} else {
    captureDevicePosition = AVCaptureDevicePositionBack;
}

// Select new camera
AVCaptureDevice *newCamera;
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

for (AVCaptureDevice *captureDevice in devices) {
    if (captureDevice.position == captureDevicePosition) {
        newCamera = captureDevice;
    }
}

if (!newCamera) return;

// Add new camera input
NSError *error;
AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&error];
if (!error && [self.captureSession canAddInput:newVideoInput]) {
    [self.captureSession addInput:newVideoInput];
}

[self.captureSession commitConfiguration];

스위프트 3

func switchCamera() {
        session?.beginConfiguration()
        let currentInput = session?.inputs.first as? AVCaptureDeviceInput
        session?.removeInput(currentInput)

        let newCameraDevice = currentInput?.device.position == .back ? getCamera(with: .front) : getCamera(with: .back)
        let newVideoInput = try? AVCaptureDeviceInput(device: newCameraDevice)
        session?.addInput(newVideoInput)
        session?.commitConfiguration()
    }

// MARK: - Private
extension CameraService {
    func getCamera(with position: AVCaptureDevicePosition) -> AVCaptureDevice? {
        guard let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as? [AVCaptureDevice] else {
            return nil
        }

        return devices.filter {
            $0.position == position
        }.first
    }
}

스위프트 4

요점 에서 전체 구현을 확인할 수 있습니다.


더 이상 사용되지 않는 경고가없는 cameraWithPosition의 Swift 3 버전 :

    // Find a camera with the specified AVCaptureDevicePosition, returning nil if one is not found
func cameraWithPosition(_ position: AVCaptureDevicePosition) -> AVCaptureDevice?
{
    if let deviceDescoverySession = AVCaptureDeviceDiscoverySession.init(deviceTypes: [AVCaptureDeviceType.builtInWideAngleCamera],
                                                          mediaType: AVMediaTypeVideo,
                                                          position: AVCaptureDevicePosition.unspecified) {

        for device in deviceDescoverySession.devices {
            if device.position == position {
                return device
            }
        }
    }

    return nil
}

원하는 경우 deviceTypes 배열을 변경하여 iPhone 7+ (듀얼 카메라)에서 새 devicesTypes를 가져올 수도 있습니다.

Here's a good read : https://forums.developer.apple.com/thread/63347


Here is an updated version of chengsam's code that includes the fix for 'Multiple audio/video AVCaptureInputs are not currently supported'.

func switchCameraTapped() {
    //Change camera source
    //Indicate that some changes will be made to the session
    session.beginConfiguration()

    //Remove existing input
    guard let currentCameraInput: AVCaptureInput = session.inputs.first else {
        return
    }


    //Get new input
    var newCamera: AVCaptureDevice! = nil
    if let input = currentCameraInput as? AVCaptureDeviceInput {
        if (input.device.position == .back) {
            newCamera = cameraWithPosition(position: .front)
        } else {
            newCamera = cameraWithPosition(position: .back)
        }
    }

    //Add input to session
    var err: NSError?
    var newVideoInput: AVCaptureDeviceInput!
    do {
        newVideoInput = try AVCaptureDeviceInput(device: newCamera)
    } catch let err1 as NSError {
        err = err1
        newVideoInput = nil
    }

    if let inputs = session.inputs as? [AVCaptureDeviceInput] {
        for input in inputs {
            session.removeInput(input)
        }
    }


    if newVideoInput == nil || err != nil {
        print("Error creating capture device input: \(err?.localizedDescription)")
    } else {
        session.addInput(newVideoInput)
    }

    //Commit all the configuration changes at once
    session.commitConfiguration()
}

// Find a camera with the specified AVCaptureDevicePosition, returning nil if one is not found
func cameraWithPosition(position: AVCaptureDevice.Position) -> AVCaptureDevice? {
    let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified)
    for device in discoverySession.devices {
        if device.position == position {
            return device
        }
    }

    return nil
}

ReferenceURL : https://stackoverflow.com/questions/20864372/switch-cameras-with-avcapturesession

반응형