I’ve keyboard like app and I’m adding each new AVAudioPlayer to NSMutableArray so I can overlay sounds.
My problem is, that delagate function
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
is not fired if there are keystrokes in short interval. If I stroke for example in 0.5s or longer interval, everything works fine. Any idea why?
I want to free memory and delete object from array when his sound play is finished.
UPDATE
.h
@interface .. <AVAudioPlayerDelegate>
{
NSMutableArray *soundObjects;
}
@property (nonatomic,strong) AVAudioPlayer *audioPlayer;
.m
-(void)playSound {
//
// play sound
//
_audioPlayer = [self loadWav:_soundID];
_audioPlayer.delegate = self;
[soundObjects addObject:_audioPlayer];
AVAudioPlayer *temp = [soundObjects objectAtIndex:soundIndex];
soundIndex = [soundObjects count];
[temp play];
}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
#ifdef DEBUG_SOUND
NSLog(@"FLAG");
soundIndex--;
[soundObjects removeObjectAtIndex:soundIndex];
#endif
}
- (AVAudioPlayer *)loadWav:(NSString *)filename {
NSURL * url = [[NSBundle mainBundle] URLForResource:filename withExtension:@"mp3"];
NSError * error;
AVAudioPlayer * player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (!player) {
#ifdef DEBUG_MODE
NSLog(@"Error loading %@: %@", url, error.localizedDescription);
#endif
} else {
[player prepareToPlay];
}
return player;
}
There are several examples of NSQueue in the developer documentation for a quick example I will use an adaptation from an Obj C Recipe book I have put together using my own work.
I hope that this helps. A few notes on the above code: you must use an autoreleasepool for each individual thread or Reference Counting (MRC or ARC) will not work because it only works within a autoreleasepool, the code that happens in the thread off the main thread should be coded like anything else it will simply execute and run to completion. If you have an infinite loop in a child thread it may not be noticeable while testing your app, however the OS will kill the app after ten minutes if I remember the current max time for a background thread correctly. More importantly and I cannot emphasize this enough if you do not create a thread specific @autoreleasepool then your objects will not be released and will eat the memory footprint even if you do not create a new object inside the new thread, when they are passed in they will gain a retain count and be maintained in memory.
I hope this helps, best of luck in your program