Created
April 21, 2014 20:01
-
-
Save 0xjmp/11154637 to your computer and use it in GitHub Desktop.
Allocations should always be executed inside of the class initialization method. Specifically for the AVAudioPlayer class, initializing in the - (id)init method and calling -prepareToPlay fully primes the player.
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 "DDViewController.h" | |
| #import <AVFoundation/AVFoundation.h> | |
| @interface DDViewController () | |
| @property (nonatomic, assign) UIButton *sayButton; | |
| @property (strong, nonatomic) AVAudioPlayer *audioPlayer; | |
| @end | |
| @implementation DDViewController | |
| @synthesize sayButton; | |
| - (void)dealloc | |
| { | |
| if (self.audioPlayer.isPlaying) | |
| [self.audioPlayer stop]; | |
| self.audioPlayer = nil; | |
| } | |
| - (id)init | |
| { | |
| self = [super init]; | |
| if (self) | |
| { | |
| sayButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; | |
| sayButton.frame = CGRectMake(0, 0, 320, 320); | |
| sayButton.backgroundColor = [UIColor orangeColor]; | |
| [sayButton setTitle:@"What the fox say?" forState:UIControlStateNormal | |
| ]; | |
| [sayButton addTarget:self action:@selector(sayButtonPressed:event:) forControlEvents:UIControlEventTouchUpInside]; | |
| [self.view addSubview:sayButton]; | |
| NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"fox" ofType:@"wav"]]; | |
| NSData *data = [NSData dataWithContentsOfURL:url]; | |
| NSError *error = nil; | |
| self.audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error]; | |
| [self.audioPlayer prepareToPlay]; // Preload buffers | |
| } | |
| return self; | |
| } | |
| - (void)sayButtonPressed:(id)sender event:(id)event | |
| { | |
| [self.audioPlayer play]; | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment