I've setup my AVAudioEngine in its own method like this:
AVAudioSession* session = [AVAudioSession sharedInstance];
[session setPreferredSampleRate:[session sampleRate] error:nil];
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[session setActive:YES error:nil];
audioEngine_ = [[AVAudioEngine alloc] init];
//tap the outputNode to create the singleton
[audioEngine_ outputNode];
NSError* error;
[audioEngine_ startAndReturnError:&error];
There is no error starting it up. I have another method to attach an AVAudioUnitMIDIInstrument from an AudioComponentDescription I've received from an Inter-App Audio instrument. My connect method looks like this:
-(void)connectInstrument:(AudioComponentDescription)desc {
instNode_ = nil;
instNode_ = [[AVAudioUnitMIDIInstrument alloc] initWithAudioComponentDescription:desc];
[audioEngine_ attachNode:instNode_];
//Crashes here
[audioEngine_ connect:instNode_ to:[audioEngine_ outputNode] format:nil];
[audioEngine_ startAndReturnError:nil];
NSLog(#"done connecting");
}
The crash gives me no useful information. I get this:
invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndexedSubscript:]: index 0 beyond bounds for empty array'
If I do a test and try to create a new mixer node and attach/connect it, there is no crash.
I have more relevant information
If I do this:
AVAudioFormat* instFormat = [instUnit_ outputFormatForBus:0];
I get the same error:
-[__NSArrayM objectAtIndexedSubscript:]: index 0 beyond bounds for empty array
It's almost as though there is no AVAudioFormat set for any output busses, nor any input busses (I checked inputFormatForBus as well). This is odd because if I do:
AudioStreamBasicDescription f1;
UInt32 outsize = sizeof(f1);
AudioUnitGetProperty(instNode_.audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &f1, &outsize);
Then f1 is a valid AudioStreamBasicDescription showing a standard 44.1khz sample rate, 32 bit float, 2 channels. So there is an output stream format, but it doesn't seem to be attached to any output bus of the AVAudioUnitMIDIInstrument instance.
EDIT - Further information
Even if I just try to access instUnite_.name I get the NSRangeException. I'm wondering now if this is a problem with how I'm getting the component description. I'm attempting to use Inter-App Audio (I have done all of the proper entitlements, capabilities, and app ID setup). This is how I am discovering Inter-App Audio components:
NSMutableArray* units = [[NSMutableArray alloc] init];
AudioComponentDescription searchDesc = { kAudioUnitType_RemoteInstrument, 0, 0, 0, 0 };
NSArray* componentArray = [[AVAudioUnitComponentManager sharedAudioUnitComponentManager] componentsMatchingDescription:searchDesc];
for(AVAudioUnitComponent* component in componentArray) {
AudioComponentDescription description = component.audioComponentDescription;
InterAppAudioUnit* unit = [[InterAppAudioUnit alloc] init];
unit.componentDescription = description;
unit.icon = AudioComponentGetIcon(component.audioComponent, 44.0f);
unit.name = component.name;
unit.avComponent = component;
[units addObject:unit];
}
_units = units;
[self.tableView reloadData];
This is all in a presented UITableViewController. After clicking one I simply execute:
[self connectInstrument:unit.componentDescription];
If I instead hand build a component description for a local unit, the AVAudioUnit is instantiated just fine and nothing crashes.
I found the answer. The AUAudioUnit object inside of the AVAudioUnit object has no output busses upon creation. I'm not sure why. You can fix it by doing this:
AUAudioUnit* auInst = instUnit_.AUAudioUnit;
NSMutableArray<AUAudioUnitBus*>* busArray = [[NSMutableArray alloc] init];
AVAudioFormat* outFormat = [[self->audioEngine_ outputNode] outputFormatForBus:0];
AUAudioUnitBus* bus = [[AUAudioUnitBus alloc] initWithFormat:outFormat error:&err];
[busArrays addObject:bus];
[[auInst outputBusses] replaceBusses:busArray];
Related
I have a pretty weird problem. I'm using coredata to save notes. I can access/save/edit all the attributes of the "Notes" entity, besides one : category.
-(void)editCategory {
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *categRequest = [NSEntityDescription entityForName:#"Notes" inManagedObjectContext:_managedObjectContext];
request.predicate = [NSPredicate predicateWithFormat:#"text = %#", noteToEdit];
[request setEntity:categRequest];
//Error handling
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error]mutableCopy];
if (mutableFetchResults == nil) {
NSLog(#"Error happened : %#", error);
}
Notes *editMe = [mutableFetchResults objectAtIndex:0];
[editMe setCategory:editCategoryText];
NSLog(#"Category from pickerview : %#", editCategoryText);
if (![_managedObjectContext save:&error]) {
NSLog(#"couldnt save : %#", error);
}
}
This line :
[editMe setCategory:editCategoryText];
is crashing. editCategoryText is a string, as the category attribute. The weird thing is that I'm using the exact same piece of code to change the title attribute, and I don't have any problem.
Log file :
2013-11-07 15:49:20.286 Simple Notes 1[16511:a0b] -[__NSCFString managedObjectContext]: unrecognized selector sent to instance 0x8dccc30
2013-11-07 15:49:20.293 Simple Notes 1[16511:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString managedObjectContext]: unrecognized selector sent to instance 0x8dccc30'
Do you have any idea why this attribute is behaving differently from the others ? Thank you.
Not at a computer so can't test this but:
Get rid of the mutableCopy. executeFetchRequest returns autoreleased objects, which you are then trying to copy, this turns into a garbage pointer, which happens to end up pointing to a string.
Actually it seems like it was a core data bug, I solved it by deleting my app in the simulator, deleting the core data model in xcode, built it again and performed a clean.
I am having an issue running GPUImage. I have modified SimpleVideoFileFilter program(replaced the filter with a chromakeyfilter) and am using my own video. My program is terminating due to the following error:
[AVAssetWriter startWriting] Cannot call method when status is 3'
I have gone through the forums but not sure why the moviewriter is closing and then someone is writing to it.
I am using iPhone4 running iOS 7.0
Any clues are greatly appreciated. Thanks much!
Check whether your destination file exists already. If it does, remove it.
I was trying to add the file to a directory which did not exist. Example : /Videos/Video.mov , leaving it just /Video.mov worked.
Ok, I have a few ideas for you.
When you say "it just shows a frame and never plays the video" we have a good indication that your entire processing pipeline from start to finish is functional exactly once, then stops working.
That tells us that you are stringing things together correctly, but some of the components don't exist longer than a single frame buffer cycle, and subsequently the whole process stops.
it looks like filter and movieWriter are scoped to the class (I'm assuming they're not properties from the lack of an underscore, _filter and _movieWriter). So they will live on after this method has finished (correct me if I'm wrong...)
I think where you are encountering trouble is your (GPUImageView*)displayView
This should probably be declared as a class property (although it could work as just a variable) and then instantiated through the nib or the viewDidLoad method of the view controller.
As you have it now, this line: GPUImageView* filterView = (GPUImageView*)displayView; is making an assignment for filterView which is not used (and therefore unnecessary). It's not clear if displayView really is an instance of GPUImageView or if it will still be in existence when the current method finishes. (in fact you say it "is a UIView that I have programmatically created")
displayView will have to be a subclass of GPUImageView for this whole thing to work, and it will have to be scoped to the class, and not the method.
Declare it like this:
#property (strong, nonatomic)GPUImageView* displayView;
and then instantiate it and add it to your view hierarchy from within viewDidLoad
movieFile1 = [[GPUImageMovie alloc] initWithURL:movieFileURL1];
movieFile2 = [[GPUImageMovie alloc] initWithURL:movieFileURL2];
movieFile2.runBenchmark = YES;
movieFile2.playAtActualSpeed = NO;
filter = [[GPUImageChromaKeyBlendFilter alloc] init];
[(GPUImageChromaKeyBlendFilter *)filter setColorToReplaceRed:0.0 green:1.0 blue:0.0];
[(GPUImageChromaKeyBlendFilter *)filter setThresholdSensitivity:0.4];
GPUImageView *filterView = (GPUImageView*)displayView;
[filter addTarget:displayView];
[movieFile1 addTarget:filter];
[movieFile2 addTarget:filter];
NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Movie.m4v"];
unlink([pathToMovie UTF8String]);
NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(1920.0, 1280.0)];
[filter addTarget:movieWriter];
movieWriter.shouldPassthroughAudio = YES;
movieFile1.audioEncodingTarget = movieWriter;
[movieFile1 enableSynchronizedEncodingUsingMovieWriter:movieWriter];
[movieWriter startRecording];
[movieFile1 startProcessing];
[movieFile2 startProcessing];
[movieWriter setCompletionBlock:^{
[filter removeTarget:movieWriter];
[movieWriter finishRecording];
}];
if (outputPath) {
finalURL = [[stongObj tempFileURL] copy];
DebugLog(#"Start Filter Processing :%#",finalURL);
DebugLog(#"movieUrl :%#",movieUrl);
// [CSUtils removeChuckFilePaths:#[outputPath]];
//Create Image Movie Object
_movieFile = [[GPUImageMovie alloc] initWithURL:outputPath];
//_movieFile = [[GPUImageMovie alloc] initWithURL:[[NSBundle mainBundle] URLForResource:#"videoviewdemo" withExtension:#"mp4"]];
_movieFile.runBenchmark = NO;
_movieFile.playAtActualSpeed = YES;
_movieFile.delegate = self;
//Movie Writer Object
_movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:finalURL size:CGSizeMake([UIScreen mainScreen].bounds.size.height,[UIScreen mainScreen].bounds.size.height)];
//_movieWriter.delegate = self;
//Create Selecetive GPU Image Filter
[stongObj setGpuOutputFilter:selectedVideoFilterType];
//Create Group Filter
groupFilter = [[GPUImageFilterGroup alloc] init];
[groupFilter addTarget:imageOutputFilter];
// Only Single Filter is implemented.
//Apply Initial and Terminal Filter
[(GPUImageFilterGroup *)groupFilter setInitialFilters:[NSArray arrayWithObject:imageOutputFilter]];
[(GPUImageFilterGroup *)groupFilter setTerminalFilter:imageOutputFilter];
//_movieWriter -> groupFilter ->_movieFile
[_movieFile addTarget:groupFilter];
[groupFilter addTarget:_movieWriter];
_movieWriter.shouldPassthroughAudio = YES;
_movieFile.audioEncodingTarget = _movieWriter;
[_movieFile enableSynchronizedEncodingUsingMovieWriter:_movieWriter];
//Start Recording
[_movieWriter startRecording];
//Start Processing
[_movieFile startProcessing];
__weak typeof(self) weekSelf=self;
[_movieWriter setCompletionBlock:^{
__strong typeof(self) stongSelf=weekSelf;
DebugLog(#"Movie Write Completed");
//Finish Recording.
[stongSelf.movieWriter finishRecording];
//Release all object
// [self releaseAllObject];
//remove movieUrl,audioUrl,outputPath
[CSUtils removeChuckFiles:#[movieUrl,audioUrl,outputPath]];
}];
[_movieFile startProcessing]; app get crash in iOS 8 on this line but working fine on iOS 7
#Seasia Creative ,I have no enough reputation to add a comment by that list,I create a new list to answer U.
I check the output URL,console log "/var~~~~/tmpmerge.mp4",so i realize that ,i miss a "/" --->"/var~~~~/tmp/merge.mp4".
If the url is no correct, project runs into the same error.
hope to help some.
I have a memory problem in an iPhone app, giving me a hard time.
Here is the error message I get:
malloc: * mmap(size=9281536) failed (error code=12)
* error: can't allocate region
I am using ARC for this app, in case that might be useful information.
The code (below) is just using a file in the Bundle in order to load a core data entity.
The strange thing is the crash happens only after more than 90 loops;
while it seems to mee that since the size of the "contents" in getting smaller and smaller, the memory request should also get smaller and smaller.
Here is the code, if any one can see a flaw please let me know.
NSString *path,*contents,*lineBuffer;
path=[[NSBundle mainBundle] pathForResource:#"myFileName" ofType:#"txt"];
contents=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
int counter=0;
while (counter<10000) {
lineBuffer=[contents substringToIndex:[contents rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location];
contents=[contents substringFromIndex:[lineBuffer length]+1];
newItem=[NSEntityDescription insertNewObjectForEntityForName:#"myEntityName"
inManagedObjectContext:context];
[newItem setValue:lineBuffer forKey:#"name"];
request=[[NSFetchRequest alloc] init];
[request setEntity: [NSEntityDescription entityForName:#"myEntityName"
inManagedObjectContext:context]];
error=nil;
[context save:&error];
counter++;
}
I finally solved the problem using NSMutableString instead of NSString for contents.
And then using : [contents deleteCharactersInRange:range];
maintaining range adequately of course.
inside the loop.
I have an NSPersistentDocument subclass using NSManagedObject subclasses for my data.
When a new document is opened, I do some initializing of data structures (trivial amount of populating fields). What I've noticed is that the Untitled document gets autosaved, and when the application re-opens, that document gets loaded. If the application quits, the user doesn't (by default) get prompted with the save dialog. If the window closes, the user does.
First question:
I want to call up the save dialog when the user quits the application. I don't want this Untitled document hanging around (under normal circumstances). I either want it saved or trashed.
I attempted to fill out:
- (void)applicationWillTerminate:(NSNotification *)aNotification
In order to trigger the document to be saved. Calling save: on the context at this point gives an error. From what I can tell, this is because the user hasn't yet saved the file on their own. In addition, calling [self close]; or [[self windowForSheet] close]; close the window without saving.
How can I force the save dialog to come up? How can I trash the untitled document?
Second question (no, I can't count):
Since when the application starts, there may or may not be an Untitled document to deal with, I'm trying to keep track of the state in another model. I've already found that the initial data (to which I referred earlier) is present when the Untitled document came up. My other model has some metadata, including a success flag/state for the populated data. Once the populated data is all in place and correct, the state indicates as such. Unfortunately, while my populated data is being loaded when the app starts with a pre-existing Untitled document, the metadata class is not.
Please excuse the roughness of the code, at this point, I'm mucking it up until I can see that it's working how I want before I polish it back off:
- (bool) createGameState {
NSEntityDescription* description = [NSEntityDescription entityForName:[GameState name] inManagedObjectContext:[self managedObjectContext]];
NSFetchRequest* req = [[NSFetchRequest alloc] init];
[req setEntity:description];
NSError *error = nil;
NSArray *array = [[self managedObjectContext] executeFetchRequest:req error:&error];
[req release];
req = nil;
GameState* result = nil;
if (array) {
NSUInteger count = [array count];
if (!count) {
// Create the new GameState.
DebugLog(#"Creating GameState");
result = [NSEntityDescription insertNewObjectForEntityForName:[GameState name] inManagedObjectContext:[self managedObjectContext]];
[result setIsLoaded:[NSNumber numberWithBool:NO]];
} else {
if (count > 1) {
NSLog(#"WARNING: Potentially Corrupt Game State. found: %lu", count);
}
result = [array objectAtIndex:0];
if ([result isLoaded]) {
[self variantLoaded];
} else {
// In this case, we have an aborted set-up. Since the game isn't
// playable, just refuse to create the GameState. This will
// force the user to create a new game.
return NO;
}
}
} else {
DebugLog(#"error: %#", error);
}
[game setState:result];
return result;
}
Note that array is always present, and count is always zero. No, I'm not explicitly calling save: anywhere. I'm relying on the standard auto-save, or the user performing a save.
EDIT:
I installed the Core Data Editor app. It turns out the issue isn't on saving the data, but on loading it. (Note: Due to another issue, the app saves as binary when instructed to save as XML, which causes much head banging.)
I've broken it down to the simplest code, which should pick up all objects of type GameState in an array. It retrieves none, despite there clearly being objects of the appropriate type in the saved file:
NSManagedObjectContext* moc = [self managedObjectContext];
NSEntityDescription* entity = [NSEntityDescription entityForName:#"GameState" inManagedObjectContext:moc];
NSFetchRequest* req = [[NSFetchRequest alloc] init];
[req setEntity:entity];
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:req error:&error];
Array is not null, but [array count] is 0.
At this point, I'm guessing it's something simple that I'm overlooking.
Second EDIT:
I added -com.apple.CoreData.SQLDebug 5 and saved as SQLite. The call to executeFetchRequest does not generate any debug logs. I do see the INSERT INTO ZGAMESTATE entry show up in the logs. It seems that executeFetchRequest is not getting passed to the backend.
Third EDIT (this one burns):
I created a new xcode project, using core data (as I had with the other). I copied just this one function (stubbing where necessary) and plopped a call to it in windowControllerDidLoadNib. In this new project, the code above works.
Found the problem.
I errantly was loading objects in Document's - (id) init call. Moved to windowControllerDidLoadNib (which is what I did in the test version) and it worked fine.
The code below is the image picker callback that runs after the user takes a photo with the camera / or picks a photo from the library.
Can someone explain to me why the first version works and second version throws an error?
The first version passes a UIImage from a synthesised UIImageView to method scaleAndRotateImage.
The second version declares a local UIImageView and passes the image to method scaleAndRotateImage.
This is the first version that works::
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
VC_Create_Preview *vc_create_preview = [[VC_Create_Preview alloc] initWithNibName:#"VC_Create_Preview" bundle:nil];
//UIImageView *temp = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
//temp.image = [self scaleAndRotateImage:temp.image];
//vc_create_preview.origImage = temp;
srcImageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
srcImageView.image = [self scaleAndRotateImage:srcImageView.image];
vc_create_preview.origImage = srcImageView;
[self.navigationController pushViewController:vc_create_preview animated:YES];
}
But the 2nd version below does not, and throws an error when calling method scaleAndRotateImage (note in debug i cannot even step "into" scaleAndRotateImage)
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
VC_Create_Preview *vc_create_preview = [[VC_Create_Preview alloc] initWithNibName:#"VC_Create_Preview" bundle:nil];
UIImageView *temp = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
temp.image = [self scaleAndRotateImage:temp.image];
vc_create_preview.origImage = temp;
//srcImageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
//srcImageView.image = [self scaleAndRotateImage:srcImageView.image];
//vc_create_preview.origImage = srcImageView;
[self.navigationController pushViewController:vc_create_preview animated:YES];
}
The error thrown by the 2nd version is
Pending breakpoint 1 - ""VC_Create_Capture.m":97" resolved
2012-01-04 20:33:52.674 MultiInterfaceTest[430:f803] -[UIImage image]: unrecognized selector sent to instance 0x68aac00
2012-01-04 20:33:52.717 MultiInterfaceTest[430:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImage image]: unrecognized selector sent to instance 0x68aac00'
*** First throw call stack:
(0x13c2052 0x1553d0a 0x13c3ced 0x1328f00 0x1328ce2 0x35df 0x211c52 0xbfaa305 0xbfbe5fd 0xc022fef 0x2dde39 0x2dd143 0x2de3cf 0x2e0a31 0x2e098c 0x2d93e7 0x41812 0x41ba2 0x28384 0x1baa9 0x12acfa9 0x13961c5 0x12fb022 0x12f990a 0x12f8db4 0x12f8ccb 0x12ab879 0x12ab93e 0x19a9b 0x23b8 0x2315)
terminate called throwing an exceptionCurrent language: auto; currently objective-c
"-[UIImage image]: unrecognized selector sent to instance 0x68aac00"
It seems that the [UIImageView image] accessor method gets called on an UIImage object. Most likely it's a memory management error: the UIImageView gets deallocated, and its memory is filled with the UIImage instance, erronously. (Unrelated: you're also leaking memory in the first approach. -pushViewController:animated: retains the view controller, so you must -release it.
This is because some where you have called image API on UIImage Class. image is a method of UIImageView class not UIImage. thats why Xcode is throwing this error.
To resolve it make sure that you are calling
So please sure that you are calling the image API on UIImage View class not UIImage. Check all the variables you have declare in your .h file and make sure you have used UIImageView class instead of UIImage.
Unrecongnized selector means that your class does not support the any image API that you have called inside your code.
Sorry Guys i found the answer.
The following is wrong because the [info objectForKey....] returns a UIImage, not a UIImageView.
Hence its probably that temp wasn't probably created hence an error from the 2nd line of the code.
UIImageView *temp = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
temp.image = [self scaleAndRotateImage:temp.image];
vc_create_preview.origImage = temp;
Thanks everyone!