Error recording to movie file with AVFoundation - ios4

This is a strange problem. I have not changed any code involving this in my project but my video recording has randomly stopped working. When I try to save to a movie to a file I get the following error:
Error Domain=NSOSStatusErrorDomain Code=-12780 "The operation couldn’t be completed. (OSStatus error -12780.)"
I start my capture with the following code:
- (void)initVideoCapture {
self.captureSession = [[AVCaptureSession alloc] init];
AVCaptureDevice *videoCaptureDevice = [self frontFacingCameraIfAvailable];
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoCaptureDevice error:nil];
[self.captureSession addInput:videoInput];
aMovieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
[self.captureSession addOutput:aMovieFileOutput];
[self detectVideoOrientation:aMovieFileOutput];
[self.captureSession setSessionPreset:AVCaptureSessionPresetMedium];
[self.captureSession startRunning];
}
I then call this method from the viewController to start recording:
- (void) startRecord {
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"yyyyMMddHHmmss"];
NSString *newDateString = [outputFormatter stringFromDate:[NSDate date]];
[outputFormatter release];
NSString * fileString = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mov",newDateString]];
recordFileURL = [[NSURL alloc] initFileURLWithPath:fileString];
[aMovieFileOutput startRecordingToOutputFileURL:recordFileURL recordingDelegate:self];
}
At this time I get the error in this function.
(void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections error:(NSError *)error
What is really weird is that it randomly works sometimes. Like, I will compile the project and it will work 100% of the time. Next time I compile it will work 0%. What could I be doing wrong? Anything obvious?

I've gotten -12780 when the orientation of the device was UIDeviceOrientationFaceUp, UIDeviceOrientationFaceDown and UIDeviceOrientationUnknown. Since a recoded video's orientation has to be portrait or landscape, it'll error out on you. I had to write a quick method that checks for those three, and just translates them to portrait.

this seems to be a bug with apple. i solved it by using AVAssetWriter and AVAssetWriterInput

Related

GPUImageVideoCamera save video on ios 7

I'm trying to achieve the square video recording like 300*300 so I choose GPUImage but its not working on IOS 7 and giving errors like [UIView nextAvailableTextureIndex]: unrecognized selector sent to instance the error starts when we build the even the sample code
when trying to save the GPUImageVideoCamera
some times its stucks at [movieWriter startRecording]; 
is the GPUImage compatible with ios 7 or we have made some changes ?
here is the code
- (void)viewDidLoad
{
[super viewDidLoad];
videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
videoCamera.horizontallyMirrorFrontFacingCamera = NO;
videoCamera.horizontallyMirrorRearFacingCamera = NO;
filter = [[GPUImageSepiaFilter alloc] init];
initWithRotation:kGPUImageRotateRightFlipVertical];
[videoCamera addTarget:filter];
GPUImageView *filterView = (GPUImageView *)self.view;
[filter addTarget:filterView];
sharing
NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Movie.m4v"];
unlink([pathToMovie UTF8String]); // If a file already exists, AVAssetWriter won't let you record new frames, so delete the old movie
NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(480.0, 640.0)];
[filter addTarget:movieWriter];
}
- (IBAction)stopRecording:(id)sender {
[filter removeTarget:movieWriter];
videoCamera.audioEncodingTarget = nil;
[movieWriter finishRecording];
}
- (IBAction)startRecording:(id)sender {
videoCamera.audioEncodingTarget = movieWriter;
[movieWriter startRecording];
[videoCamera startCameraCapture];
}
My guess is that you modified the .xib or storyboard and didn't set the class of the view that is showing the camera preview to GPUImageView.

Unable to Integrate Instagram in iOS App

i am unable to post my photos on instagram using ios App. I got the following code from a post here on stackoverflow but it does not work. When Instagram starts, it displays error unable to open file. kindly help me.
NSURL *instagramURL = [NSURL URLWithString:#"instagram://location?id=1"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"Image.ig"];
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:#"Icon.png"]);
[imageData writeToFile:savedImagePath atomically:YES];
NSURL *imageUrl = [NSURL fileURLWithPath:savedImagePath];
docController = [[UIDocumentInteractionController alloc] init];
docController.delegate = self;
[docController retain];
docController.UTI = #"com.instagram.photo";
[docController setURL:imageUrl];
[docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}else{
UIAlertView *errorToShare = [[UIAlertView alloc] initWithTitle:#"Instagram unavailable " message:#"You need to install Instagram in your device in order to share this image" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorToShare show];
[errorToShare release];
}
Minimum resolution for instagram is 612x612. Always JPG.
For the sake of completion, the minimum resolution remains at 612x612 (this is due to displaying images on retina devices), but Instagram now supports both JPEG and PNG images. All non-square images sent to Instagram must be cropped before posting.

A Core-Data Relashionship not working after stopping the app

I have had one issue with Core Data and Relationship. Since this has kept me without a solution for a while and has at the same time been easy to locate I have made a tiny sample application to reproduce the problem.
Under XCode I created a barebone Window-based application, checking "Use Core Data for storage".
I called this application "CDR" for Core-Data-Relationship.
I then added a subclass of UIViewController called CDR_ViewController; as I usually do.
Here is the relevant code that I added :
First in CDR_ViewController.h :
#import <UIKit/UIKit.h>
#import "AppDelegate_Shared.h"
#interface CDR_ViewController : UIViewController {
UILabel *cdrLabel;
NSManagedObject *currentItem;
}
#property (nonatomic, retain) IBOutlet UILabel *cdrLabel;
-(IBAction) handleButtonClick:(id)sender;
#end
Then in CDR_ViewController.m the viewDidLoad method is as follow :
- (void)viewDidLoad {
[super viewDidLoad];
NSFetchRequest *request;
NSError *error;
AppDelegate_Shared *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
request=[[NSFetchRequest alloc] init];
[request setEntity: [NSEntityDescription entityForName:#"CDR_Entity" inManagedObjectContext:context]];
error=nil;
NSUInteger count = [context countForFetchRequest:request error:&error];
[request release];
if (count!=0) {
request=[[NSFetchRequest alloc] init];
[request setEntity: [NSEntityDescription entityForName:#"CDR_Entity" inManagedObjectContext:context]];
error=nil;
NSArray *objects=[context executeFetchRequest:request error:&error];
NSLog(#"Error:%#",error);
[request release];
currentItem=[objects objectAtIndex:0];
return;
}
NSManagedObject *newItemOne,*newItemTwo,*newItemThree;
request=[[NSFetchRequest alloc] init];
[request setEntity: [NSEntityDescription entityForName:#"CDR_Entity" inManagedObjectContext:context]];
newItemOne=[NSEntityDescription insertNewObjectForEntityForName:#"CDR_Entity" inManagedObjectContext:context];
newItemTwo=[NSEntityDescription insertNewObjectForEntityForName:#"CDR_Entity" inManagedObjectContext:context];
newItemThree=[NSEntityDescription insertNewObjectForEntityForName:#"CDR_Entity" inManagedObjectContext:context];
[newItemOne setValue:[NSNumber numberWithInteger:1] forKey:#"Value"];
[newItemTwo setValue:[NSNumber numberWithInteger:2] forKey:#"Value"];
[newItemThree setValue:[NSNumber numberWithInteger:3] forKey:#"Value"];
[newItemOne setValue:newItemThree forKey:#"Previous"];
[newItemOne setValue:newItemTwo forKey:#"Next"];
[newItemTwo setValue:newItemOne forKey:#"Previous"];
[newItemTwo setValue:newItemThree forKey:#"Next"];
[newItemThree setValue:newItemTwo forKey:#"Previous"];
[newItemThree setValue:newItemOne forKey:#"Next"];
error=nil;
[context save:&error];
[request release];
currentItem=newItemOne;
}
And the viewWillAppear method is as follow :
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
cdrLabel.text=[NSString stringWithFormat:#"%#",[currentItem valueForKey:#"Value"]];
}
Finally the handleButtonClick method is as follow :
-(IBAction) handleButtonClick:(id)sender
{
if (((UIButton*)sender).tag==101) {// Previous item.
currentItem=[currentItem valueForKey:#"Previous"];
} else /*(((UIButton*)sender).tag==102)*/ {// Next item.
currentItem=[currentItem valueForKey:#"Next"];
}
cdrLabel.text=[NSString stringWithFormat:#"%#",[currentItem valueForKey:#"Value"]];
}
The CDR_ViewController.xib contains one Label and two buttons.
This code works fine for start, meaning just after I compile the app and reset the contents of the iPhone simulator.
I can then cycle the contents of the label : 1,2,3,1,2,3,1,2,3 ---etc… and backward with the buttons.
As soon as I terminate the application using Command-Q. When I want to start it again, it crashes on :
currentItem=[currentItem valueForKey:#"Previous"];
or:
currentItem=[currentItem valueForKey:#"Next"];
inside the handleButtonClick method.
And it is the same when I put the app on my iPod touch.
Can anyone see in my code anything that could explain this behavior?
If you terminate an app in the simulator by stopping it, a opposed to clicking the home button in the simulator or otherwise, then the program is sent a SIGKILL message which immediately stop it running. Your application delegate methods (will terminate, will enter background etc) will not be called.
In all likelihood this will have meant that your managed object context has not been saved, so when re-running the app the object graph cannot be restored properly. In your sample app, add another button which saves the context. If you click this button, then terminate your app, does that solve the problem?

Detecting blow in the iPhone Mic with Cocos2D

I'm using Cocos2D and the system particles and I hope I wrote this correctly in English.
I'm having problems to recognize sounds with the iPhone mic in certain way.
I have different sections in my application, in one of them I use the mic to detect if someone is "blowing air" into the mic. This part works fine at the beginning, but if you go to other section of the app that plays sound and later you return to this area and try to blow air, it won't work.
I debuged the code, and the levelTimeCallback is always working even if I'm not in this scene. I don't really know what's happening. I've stopped all sounds using
[[SimpleAudioEngine sharedEngine] stopBackgroundMusic];
Anyone knows what I'm doing wrong? BTW works perfectly in simulator, but not in iPhone.
The recorder is set in the onEnter method
-(void) onEnter {
[super onEnter];
NSURL *url = [NSURL fileURLWithPath:#"/dev/null"];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey,
nil];
NSError *error;
recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
if (recorder) {
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
[recorder record];
levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.03 target: self selector: #selector(levelTimerCallback:) userInfo: nil repeats: YES];
NSLog(#"I'm in the recorder");
} else
NSLog(#"recorder error");
}
This is the levelTimerCallback method were the sound is "checked"
- (void)levelTimerCallback:(NSTimer *)timer {
[recorder updateMeters];
const double ALPHA = 0.05;
double peakPowerForChannel = pow(10, (0.05 * [recorder peakPowerForChannel:0]));
lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;
if (lowPassResults > 0.55)
{
NSLog(#"Mic blow detected");
self.emitter = [[CCParticleExplosion alloc] initWithTotalParticles:5];
[self addChild: emitter z:1];
emitter.texture = [[CCTextureCache sharedTextureCache] addImage: #"hoja.png"];
emitter.autoRemoveOnFinish = YES;
}
NSLog(#"Inside levelTimerCallback");}
Same problem.
There are 2 ways to solved this.
1: Use AVAudioPlayer to play music or sound effect.
2: Add #import "CDAudioManager.h"to AppDelegate.m and Add
[CDAudioManager initAsynchronously:kAMM_PlayAndRecord];
to
- (void) applicationDidFinishLaunching:(UIApplication*)application`
source
Finally, after reading the Audio Session cookbook and different kind of post related I found the solution. Jus put this code block in the init method:
UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
AudioSessionSetActive(true);

AVPlayer does not retain AVPlayerItem

Does somebody know why this code is crashing somewhere in the release pool (after 'eject' is called)?
I saw in AVPlayer class reference that the 'currentItem' property is NOT declared as 'retain' http://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVPlayer_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40009530-CH1-SW21
Is it a bug in the AVPlayer class or should I retain it somewhere else?
Thanks!
- (void) viewDidLoad {
NSURL *url = [NSURL URLWithString:#"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
playerItem = [[AVPlayerItem alloc] initWithURL:url];
player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
}
- (IBAction) eject {
[player release];
[playerItem release];
}
I typically use this to setup a player:
if (!self.player) {
player = [[AVPlayer alloc] init];
}
[self.player replaceCurrentItemWithPlayerItem:[AVPlayerItem playerItemWithURL:videoURL]];
I believe that AVPlayer retains AVPlayerItem in initWithPlayerItem: function, so you are possibly leaking memory with your AVPlayerItem. "currentItem" is readonly property and should not be "retain" which is only for writable properties.

Resources