Monday, December 31, 2012

[iOS] AVAudioPlayer delay first play

If your application's effect sounds is played a little late than actual action, you may need to load the sound file on the viewDidLoad for prepare to play.

Example code is below.

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupArray];
    [self imgAlloc];
    courseNameField.text = courseName;
    
    NSString *backgroundSoundpath = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"/ahhh.mp3"];
    NSError *err00;
    ahhhPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:backgroundSoundpath] error:&err00];
    ahhhPlayer.currentTime = 0;
    [ahhhPlayer prepareToPlay];
    
    NSString *whoopiepath = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"/whoopie.wav"];
    NSError *err01;
    whoopiePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:whoopiepath] error:&err01];
    whoopiePlayer.currentTime = 0;
    [whoopiePlayer prepareToPlay];
    
    NSString *jumppath = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"/WhoopFlp.wav"];
    NSError *err02;
    jumpPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:jumppath] error:&err02];
    jumpPlayer.currentTime = 0;
    
    gameTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(gameUpdate) userInfo:nil repeats:YES];
    
    [self animateRunning];
    [self backgroundSound];
    
}

No comments: