用avcapturesession切换相机

时间:2013-12-31 23:54:43

标签: ios avcapturesession front-camera

在此处使用本教程: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中,如果我将fontCamera设置为YES,则会显示前置摄像头,但无法切换回来,反之亦然。

有关如何正确切换的任何想法?

6 个答案:

答案 0 :(得分:98)

首先需要从AVCaptureSession中删除现有的AVCameraInput,然后将新的AVCameraInput添加到AVCaptureSession。以下适用于我(在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;
}

答案 1 :(得分:21)

Swift 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编辑(结合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
}

Swift版本到@ NES_4Life的回答:

@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
}

答案 2 :(得分:11)

根据以前的答案,我使用一些验证和一个特定的更改制作了我自己的版本,当前的摄像头输入可能不是捕获会话输入的第一个对象,所以我改变了这个:

//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 :(得分:3)

Swift 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 :(得分:0)

swift 3版本的cameraWithPosition没有弃用警告:

    // 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+(双摄像头)获取新的设备类型。

这里有一个很好的阅读:https://forums.developer.apple.com/thread/63347

答案 5 :(得分:0)

以下是chengsam代码的更新版本,其中包含目前尚未支持多种音频/视频AVCaptureInput的修复程序'。

play.filters.disabled += "play.filters.headers.SecurityHeadersFilter"