Created
April 24, 2013 17:21
-
-
Save alexch/5453875 to your computer and use it in GitHub Desktop.
AVAudioPlayer makes a loud POP if you tell it to play when it's already playing. So let's make an instance pool and let the other one play out and grab one that's not currently playing. Note that the two sounds will overlap.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(id)initWithFile: (NSString*)file | |
{ | |
if (self = [super init]) { | |
self.file = file; | |
NSString* path = [[NSBundle mainBundle] pathForResource:self.file ofType:@"caf"]; | |
self.fileUrl = [NSURL fileURLWithPath:path]; | |
NSAssert(self.fileUrl, @"URL is valid."); | |
self.players = [NSMutableArray arrayWithCapacity:2]; | |
[self createPlayer]; | |
[self createPlayer]; | |
} | |
return self; | |
} | |
// create a new player and add it to the pool | |
-(AVAudioPlayer*)createPlayer | |
{ | |
NSError *error; | |
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.fileUrl error:&error]; | |
if (player == nil || error) | |
NSLog(@"%@", [error description]); | |
player.delegate = self; | |
[player prepareToPlay]; | |
[self.players addObject:player]; | |
return player; | |
} | |
// Find an unused player, or make a new one. We need a pool since AVAudioPlayer makes a POP! if you call play before it's done with the previous play. | |
-(AVAudioPlayer*)grabPlayer | |
{ | |
for (AVAudioPlayer *player in self.players) { | |
if (!player.isPlaying) { | |
return player; | |
} | |
} | |
return [self createPlayer]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment