I'm trying to record a video (without displaying the camera) and save it. But the video being saved is not saving in the right orientation. I've tried forcing the UIViewController to be a certain orientation but that didn't help. All videos are being recorded in portrait. My code is below:
session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
session.sessionPreset = AVCaptureSessionPresetHigh;
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *cam in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo])
{
if (cam.position == AVCaptureDevicePositionFront)
device = cam;
}
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
// Handle the error appropriately.
NSLog(#"ERROR: trying to open camera: %#", error);
}
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *outputpathofmovie = [[documentsDirectoryPath stringByAppendingPathComponent:#"RecordedVideo"] stringByAppendingString:#".mp4"];
outputURL = [[NSURL alloc] initFileURLWithPath:outputpathofmovie];
[self deleteTempVideos];
[session addInput:input];
[session addInput:audioInput];
[session commitConfiguration];
[session startRunning];
movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
NSLog(#"%#", movieFileOutput.connections);
AVCaptureConnection *videoConnection = nil;
for ( AVCaptureConnection *connection in [movieFileOutput connections] )
{
NSLog(#"%#", connection);
for ( AVCaptureInputPort *port in [connection inputPorts] )
{
NSLog(#"%#", port);
if ( [[port mediaType] isEqual:AVMediaTypeVideo] )
{
videoConnection = connection;
}
}
}
if([videoConnection isVideoOrientationSupported]) // **Here it is, its always false**
{
[videoConnection setVideoOrientation:[[UIDevice currentDevice] orientation]];
}
NSLog(#"%#", videoConnection);
[session addOutput:movieFileOutput];
[movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];
It turns out you have to add the connections' orientation to the AVCaptureMovieFileOutput after it is added to the session.
session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
session.sessionPreset = AVCaptureSessionPresetHigh;
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *cam in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo])
{
if (cam.position == AVCaptureDevicePositionFront)
device = cam;
}
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
// Handle the error appropriately.
NSLog(#"ERROR: trying to open camera: %#", error);
}
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *outputpathofmovie = [[documentsDirectoryPath stringByAppendingPathComponent:#"RecordedVideo"] stringByAppendingString:#".mp4"];
outputURL = [[NSURL alloc] initFileURLWithPath:outputpathofmovie];
[self deleteTempVideos];
[session addInput:input];
[session addInput:audioInput];
[session commitConfiguration];
[session startRunning];
movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
[session addOutput:movieFileOutput];
AVCaptureConnection *videoConnection = nil;
for ( AVCaptureConnection *connection in [movieFileOutput connections] )
{
NSLog(#"%#", connection);
for ( AVCaptureInputPort *port in [connection inputPorts] )
{
NSLog(#"%#", port);
if ( [[port mediaType] isEqual:AVMediaTypeVideo] )
{
videoConnection = connection;
}
}
}
if([videoConnection isVideoOrientationSupported]) // **Here it is, its always false**
{
[videoConnection setVideoOrientation:[[UIDevice currentDevice] orientation]];
}
[movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];
**
Try changing its orientation just before starting recording.
**
if let videoConnection = fileOutput.connection(with: .video) {
let newOrientation: AVCaptureVideoOrientation
switch UIDevice.current.orientation {
case .portrait:
newOrientation = .portrait
case .portraitUpsideDown:
newOrientation = .portraitUpsideDown
case .landscapeLeft:
newOrientation = .landscapeRight
case .landscapeRight:
newOrientation = .landscapeLeft
default :
newOrientation = .portrait
}
videoConnection.videoOrientation = newOrientation
self.fileOutput.startRecording(to: URL(fileURLWithPath: filePath), recordingDelegate: self)
}
where,
var fileOutput : AVCaptureMovieFileOutput!
Try something like this:
#import <AVFoundation/AVFoundation.h>
AVCaptureConnection *captureConnection = <#A capture connection#>;
if ([captureConnection isVideoOrientationSupported])
{
AVCaptureVideoOrientation orientation = AVCaptureVideoOrientationLandscapeLeft;
[captureConnection setVideoOrientation:orientation];
}
http://developer.apple.com/library/ios/#qa/qa1744/_index.html#//apple_ref/doc/uid/DTS40011134
Thank you Destiny Dawn, incase anyone is looking for the code for Xamarin ios:
AVCaptureConnection videoConnection = null;
foreach(AVCaptureConnection connection in _videoOutput.Connections)
{
foreach ( AVCaptureInputPort port in connection.InputPorts)
{
if (port.MediaType == AVMediaType.Video)
{
videoConnection = connection;
break;
}
}
}
if (videoConnection != null) {
if (videoConnection.SupportsVideoOrientation) {
videoConnection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight;
}
}
Related
My app uses the front facing camera to record video. I have the Preview Layer successfully set up to show it in landscape right mode, which is the only way the app will run. How do I make sure the Movie output displays correctly?
session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
session.sessionPreset = AVCaptureSessionPresetMedium;
CALayer *viewLayer = self.vImagePreview.layer;
NSLog(#"viewLayer = %#", viewLayer);
self.captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
self.captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
self.captureVideoPreviewLayer.frame = self.vImagePreview.bounds;
[self.captureVideoPreviewLayer setCornerRadius:14];
[self.captureVideoPreviewLayer setBorderWidth:3.0];
[self.captureVideoPreviewLayer setBorderColor:[[UIColor whiteColor] CGColor]];
self.captureVideoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
[[vImagePreview layer] setCornerRadius:14];
[[vImagePreview layer] setBorderWidth:3.0];
[[vImagePreview layer] setBorderColor:[[UIColor whiteColor] CGColor]];
[self.vImagePreview.layer addSublayer:self.captureVideoPreviewLayer];
AVCaptureDevice *device = [self frontFacingCameraIfAvailable];
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
// Handle the error appropriately.
NSLog(#"ERROR: trying to open camera: %#", error);
}
AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
NSError *error2 = nil;
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioCaptureDevice error:&error2];
AVCaptureMovieFileOutput *movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
NSString *archives = [documentsDirectoryPath stringByAppendingPathComponent:#"archives"];
NSString *editedfilename = [[selectedCountry lastPathComponent] stringByDeletingPathExtension];
NSString *datestring = [[editedfilename stringByAppendingString:#" "] stringByAppendingString:currentTime];
NSLog(#"%#", datestring);
NSString *outputpathofmovie = [[archives stringByAppendingPathComponent:datestring] stringByAppendingString:#".mp4"];
NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:outputpathofmovie];
[session addInput:input];
[session addInput:audioInput];
[session addOutput:movieFileOutput];
[session commitConfiguration];
[session startRunning];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];
NSLog(#"OutputURL%#", outputURL);
}
-(void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
switch (orientation) {
case UIInterfaceOrientationPortrait:
[self.captureVideoPreviewLayer.connection setVideoOrientation:AVCaptureVideoOrientationPortrait];
break;
case UIInterfaceOrientationPortraitUpsideDown:
[self.captureVideoPreviewLayer.connection setVideoOrientation:AVCaptureVideoOrientationPortraitUpsideDown];
break;
case UIInterfaceOrientationLandscapeLeft:
[self.captureVideoPreviewLayer.connection setVideoOrientation:AVCaptureVideoOrientationLandscapeLeft];
break;
case UIInterfaceOrientationLandscapeRight:
[self.captureVideoPreviewLayer.connection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight];
break;
}
}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error {
//finished
NSLog(#"ErrorMessage%#", error);
}
-(IBAction)endcall {
[player stop];
[session stopRunning];
}
-(AVCaptureDevice *)frontFacingCameraIfAvailable
{
NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
AVCaptureDevice *captureDevice = nil;
for (AVCaptureDevice *device in videoDevices)
{
if (device.position == AVCaptureDevicePositionFront)
{
captureDevice = device;
break;
}
}
// couldn't find one on the front, so just get the default video device.
if ( ! captureDevice)
{
captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
}
return captureDevice;
}
- ( void ) captureOutput: ( AVCaptureOutput * ) captureOutput
didOutputSampleBuffer: ( CMSampleBufferRef ) sampleBuffer
fromConnection: ( AVCaptureConnection * ) connection
{
connection.videoOrientation = //ur desired mode;
}
try implementing the above delegate method
I'm using AV to record video via my app, and I have a button that swaps between the camera view being front and back camera, with back being the default. Switching from back to front works just fine. However, switching then from front to back causes the app to crash.
- (IBAction)btnSwapCamerasClicked:(id)sender {
//Change camera source
if(session)
{
//Indicate that some changes will be made to the session
[session beginConfiguration];
//Remove existing input
AVCaptureInput* currentCameraInput = [session.inputs objectAtIndex:0];
[session 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
{
//THIS IS THE SPOT THAT CRASHES.
[session addInput:newVideoInput];
}
//Commit all the configuration changes at once
[session commitConfiguration];
}
}
The crash occurs under [session addInput:newVideoInput]; and I am returned the following error text:
2015-03-03 11:25:59.566 The SWAT App Beta[1769:365194] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* Multiple audio/video AVCaptureInputs are not currently supported.'
*** First throw call stack:
(0x185c002d4 0x1975c80e4 0x1843ad39c 0x1843accd4 0x10004ac14 0x18a818fb4 0x18a80201c 0x18a818950 0x18a8185dc 0x18a811a74 0x18a7e57f0 0x18aa85274 0x18a7e3d04 0x185bb8250 0x185bb74f4 0x185bb55a4 0x185ae1404 0x18f4eb6fc 0x18a84a2b4 0x10004bb70 0x197c6ea08)
libc++abi.dylib: terminating with uncaught exception of type NSException
I'm not entirely sure why there seems to be multiple inputs, since in the code I listed I removed the old input, and it works just fine for back to front. Not sure why front to back is making the app kill itself.
Any ideas?
I solved my issue by rewriting the code for switching cameras to something I wrote proprietarily. I created an NSString named currentCam that I change the text to between "Back" and "Front" depending on the current situation. Code below:
- (IBAction)btnSwapCamerasClicked:(id)sender {
[session beginConfiguration];
if ([currentCam isEqualToString:#"Back"])
{
NSArray *inputs = [session inputs];
for (AVCaptureInput *input in inputs)
{
[session removeInput:input];
}
//Video input
AVCaptureDevice *newCamera = nil;
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
//Audio input
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil];
NSError *err = nil;
AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
if(!newVideoInput || err)
{
NSLog(#"Error creating capture device input: %#", err.localizedDescription);
}
else
{
[session addInput:newVideoInput];
[session addInput:audioInput];
newVideoInput = nil;
audioInput = nil;
audioDevice = nil;
newCamera = nil;
inputs = nil;
}
currentCam = #"Front";
}
else if ([currentCam isEqualToString:#"Front"])
{
NSArray *inputs = [session inputs];
for (AVCaptureInput *input in inputs)
{
[session removeInput:input];
}
//Video input
AVCaptureDevice *newCamera = nil;
newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
//Audio input
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil];
NSError *err = nil;
AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
if(!newVideoInput || err)
{
NSLog(#"Error creating capture device input: %#", err.localizedDescription);
}
else
{
[session addInput:newVideoInput];
[session addInput:audioInput];
newVideoInput = nil;
audioInput = nil;
audioDevice = nil;
newCamera = nil;
inputs = nil;
}
currentCam = #"Back";
}
else
{
//Camera is some weird third camera that doesn't exist yet! :O
NSLog(#"wat");
}
[session commitConfiguration];
}
only this much code can work
- (IBAction)switchCamera:(id)sender {
[captureSession beginConfiguration];
NSArray *inputs = [captureSession inputs];
//Remove all inputs
for (AVCaptureInput *input in inputs)
{
[captureSession removeInput:input];
}
//Video input
AVCaptureDevice *newCamera = nil;
if ([currentCam isEqualToString:#"Back"]){
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
currentCam = #"Front";
}else{
newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
currentCam = #"Back";
}
//Audio input
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil];
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];
[captureSession addInput:audioInput];
}
[captureSession commitConfiguration];
}
i am using custom camera view for my app. but when i am changing my view its not responding well i can't able to see my view whatever changes its stop showing live view if i am not changing then its working just fine ,i don`t know i try alot were i am doing mistake or missing something. my code is
-(void)abdbcam
{
session=[[AVCaptureSession alloc]init];
[session setSessionPreset:AVCaptureSessionPresetPhoto];
/* AVCaptureDevice *inputDevice=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error;
AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];
if([session canAddInput:deviceInput])
{
[session addInput:deviceInput];
}*/
NSArray *devices = [AVCaptureDevice devices];
AVCaptureDevice *frontcamera;
AVCaptureDevice *backcamera;
for (AVCaptureDevice *device in devices)
{
NSLog(#"Device Nmae %#",[device localizedName]);
if ([device hasMediaType:AVMediaTypeVideo])
{
if ([device position] == AVCaptureDevicePositionBack)
{
NSLog(#"device position: bAck");
backcamera = device;
}
else
{
NSLog(#"device position : front");
frontcamera = device;
}
}
}
if (!FrontCamera)
{
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:backcamera error:&error];
if (!input)
{
NSLog(#"error: trying to open camera: %#", error);
}
[session addInput:input];
}
if (FrontCamera) {
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:frontcamera error:&error];
if (!input) {
NSLog(#"error: trying to open camera: %#", error);
}
[session addInput:input];
}
AVCaptureVideoPreviewLayer *previewLayer=[[AVCaptureVideoPreviewLayer alloc]initWithSession:session];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
CALayer *rootLayer = [[self view]layer];
[rootLayer setMasksToBounds:YES];
CGRect frame=self.camerarole.frame;
[previewLayer setFrame:frame];
[rootLayer insertSublayer:previewLayer atIndex:0];
stillImageOutput=[[AVCaptureStillImageOutput alloc]init];
NSDictionary *outputSetting=[[NSDictionary alloc]initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
[stillImageOutput setOutputSettings:outputSetting];
[session addOutput:stillImageOutput];
[session startRunning];
}
// now my segment controller code is
- (IBAction)switchcamera:(id)sender {
if (cameraswitch.selectedSegmentIndex == 0) {
FrontCamera = YES;
[self abdbcam];
}
if (cameraswitch.selectedSegmentIndex == 1) {
[self abdbcam];
}
please have a look and suggest me if i am doing any mistake
So I've already implemented custom camera switch. Check this code below:
isUsingFrontFacingCamera is a bool flag, too detect which camera are you using at the moment
- (void) switchCam{
if (![self cameraIsRunning])
return;
AVCaptureDevicePosition desiredPosition;
if (isUsingFrontFacingCamera)
desiredPosition = AVCaptureDevicePositionBack;
else
desiredPosition = AVCaptureDevicePositionFront;
for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
if ([d position] == desiredPosition) {
[[captureVideoPreviewLayer session] beginConfiguration];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil];
for (AVCaptureInput *oldInput in [[captureVideoPreviewLayer session] inputs]) {
[[captureVideoPreviewLayer session] removeInput:oldInput];
}
[[captureVideoPreviewLayer session] addInput:input];
[[captureVideoPreviewLayer session] commitConfiguration];
break;
}
}
isUsingFrontFacingCamera = !isUsingFrontFacingCamera;
}
This code worked for while i am working. i am posting this because it will be helpful for anyone.
NSArray *inputs = session.inputs;
for ( AVCaptureDeviceInput *input in inputs ) {
AVCaptureDevice *device = input.device;
if ( [device hasMediaType:AVMediaTypeVideo] ) {
AVCaptureDevicePosition position = device.position;
AVCaptureDevice *newCamera = nil;
AVCaptureDeviceInput *newInput = nil;
if (position == AVCaptureDevicePositionFront)
newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
else
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
// beginConfiguration ensures that pending changes are not applied immediately
[session beginConfiguration];
[session removeInput:input];
[session addInput:newInput];
// Changes take effect once the outermost commitConfiguration is invoked.
[session commitConfiguration];
break;
}
}
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for ( AVCaptureDevice *device in devices )
if ( device.position == position )
return device;
return nil;
}
I make a Photo Capture and Video Record customise view (2 features in one view).
Init view:
_session = [[AVCaptureSession alloc] init];
_session.sessionPreset = AVCaptureSessionPreset640x480;
_captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_session];
_captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
_captureVideoPreviewLayer.frame = _previewView.layer.bounds; // parent of layer
[_previewView.layer addSublayer:_captureVideoPreviewLayer];
AVCaptureDevice *videoDevice = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo][0];
if ([videoDevice isFlashAvailable] && videoDevice.flashActive && [videoDevice lockForConfiguration:nil]) {
videoDevice.flashMode = AVCaptureFlashModeOff;
[videoDevice unlockForConfiguration];
}
NSError * error = nil;
AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
if (!input) {
if (_delegate && [_delegate respondsToSelector:#selector(customCameraViewDidLoadFailed)]) {
[_delegate customCameraViewDidLoadFailed];
}
}
if ([_session canAddInput:input]) {
[_session addInput:input];
}
AVCaptureDevice *audioDevice = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject];
AVCaptureDeviceInput *audioDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
if (!audioDeviceInput) {
if (_delegate && [_delegate respondsToSelector:#selector(customCameraViewDidLoadFailed)]) {
[_delegate customCameraViewDidLoadFailed];
}
}
if ([_session canAddInput:audioDeviceInput]) {
[_session addInput:audioDeviceInput];
}
_stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil];
[_stillImageOutput setOutputSettings:outputSettings];
if ([_session canAddOutput:_stillImageOutput]) {
[_session addOutput:_stillImageOutput];
}
_movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
if ([_session canAddOutput:_movieFileOutput])
{
[_session addOutput:_movieFileOutput];
AVCaptureConnection *connection = [_movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
if ([connection isVideoStabilizationSupported]) {
[connection setEnablesVideoStabilizationWhenAvailable:YES];
}
}
[_session startRunning];
In Capture method:
_session.sessionPreset = AVCaptureSessionPreset640x480;
_isCapturing = YES;
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in _stillImageOutput.connections)
{
for (AVCaptureInputPort *port in [connection inputPorts])
{
if ([[port mediaType] isEqual:AVMediaTypeVideo] )
{
videoConnection = connection;
break;
}
}
if (videoConnection) {
break;
}
}
[_loadingView startAnimating];
[_stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
{
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
UIImage * capturedImage = [[UIImage alloc]initWithData:imageData scale:1];
_isCapturing = NO;
imageData = nil;
[_loadingView stopAnimating];
if (_delegate && [_delegate respondsToSelector:#selector(customCameraView:didFinishCaptureImage:)]) {
[_delegate customCameraView:self didFinishCaptureImage:capturedImage];
}
}];
I'm facing a problem that, the first photo/video when I capture, it's always BLACK photo, video.
Can you help me to solve this problem.
Thanks a lot!
I'm trying to use the back camera off my iphone with AVCaptureDevice. I tried both AVCaptureDevicePositionBack and AVCaptureDevicePositionFront but it still uses the FrontCamera no matter what.
This is my code:
- (void)setupCamera
{
_captureDevice = nil;
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices)
{
if (device.position == AVCaptureDevicePositionBack)
{
_captureDevice = device;
break;
}
}
}
- (void)turnCameraOn
{
NSError *error;
_session = [[AVCaptureSession alloc] init];
[_session beginConfiguration];
[_session setSessionPreset:AVCaptureSessionPresetMedium];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:_captureDevice error:&error];
if (input == nil)
NSLog(#"%#", error);
[_session addInput:input];
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
[output setSampleBufferDelegate:self queue:dispatch_queue_create("myQueue", NULL)];
output.videoSettings = #{(id)kCVPixelBufferPixelFormatTypeKey:#(kCVPixelFormatType_32BGRA)};
output.alwaysDiscardsLateVideoFrames = YES;
[_session addOutput:output];
[_session commitConfiguration];
[_session startRunning];
}
- (void)turnCameraOff
{
[_session stopRunning];
_session = nil;
}
Use the following code:
AVCaptureDevicePosition desiredPosition;
if (isUsingFrontFacingCamera)
desiredPosition = AVCaptureDevicePositionBack;
else
desiredPosition = AVCaptureDevicePositionFront;
for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
if ([d position] == desiredPosition) {
[[captureVideoPreviewLayer session] beginConfiguration];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil];
for (AVCaptureInput *oldInput in [[captureVideoPreviewLayer session] inputs]) {
[[captureVideoPreviewLayer session] removeInput:oldInput];
}
[[captureVideoPreviewLayer session] addInput:input];
[[captureVideoPreviewLayer session] commitConfiguration];
break;
}
}