Skip to content

Instantly share code, notes, and snippets.

@alexch
Created April 24, 2013 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexch/5453875 to your computer and use it in GitHub Desktop.
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.
-(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