Skip to content

Instantly share code, notes, and snippets.

@0xjmp
Created April 21, 2014 20:01
Show Gist options
  • Select an option

  • Save 0xjmp/11154637 to your computer and use it in GitHub Desktop.

Select an option

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.
#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