Created
November 23, 2010 07:57
-
-
Save djones/711433 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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"]; |
This file contains hidden or 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
#import <AVFoundation/AVFoundation.h> | |
@interface Player : NSObject <AVAudioPlayerDelegate> { | |
AVAudioPlayer *_audioPlayer; | |
BOOL preloading; | |
} | |
@property (nonatomic) BOOL preloading; | |
- (void)playSound:(NSString *)soundName ofType:(NSString *)type; | |
@end |
This file contains hidden or 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
#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