Skip to content

Instantly share code, notes, and snippets.

@djones
Created November 23, 2010 07:57
Show Gist options
  • Save djones/711433 to your computer and use it in GitHub Desktop.
Save djones/711433 to your computer and use it in GitHub Desktop.
// Step 1: Place sound files into your resources folder.
// Step 2: right mouse click on "Frameworks" in your project, then select Add -> Existing Framework. Choose "AVFoundation.framework"
#import "Player.h"
// Example use
Player *player = [[Player alloc] init];
// Preload sounds
player.preloading = YES;
[player playSound:@"boom" ofType:@"mp3"];
[player playSound:@"whack" ofType:@"mp3"];
[player playSound:@"blonk" ofType:@"mp3"];
[player playSound:@"bang" ofType:@"mp3"];
player.preloading = NO;
// Play sound - plays immediately as sound has been preloaded
[player playSound:@"whack" ofType:@"mp3"];
#import <AVFoundation/AVFoundation.h>
@interface Player : NSObject <AVAudioPlayerDelegate> {
AVAudioPlayer *_audioPlayer;
BOOL preloading;
}
@property (nonatomic) BOOL preloading;
- (void)playSound:(NSString *)soundName ofType:(NSString *)type;
@end
#import "Player.h"
@implementation Player
@synthesize preloading;
- (void)playSound:(NSString *)soundName ofType:(NSString *)type {
if([_audioPlayer isPlaying]){
[_audioPlayer stop];
_audioPlayer = nil;
}
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:soundName ofType:type]];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
_audioPlayer.delegate = self;
if(preloading){
[_audioPlayer prepareToPlay];
} else {
[_audioPlayer play];
}
}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[_audioPlayer release];
_audioPlayer = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment