colindunn colindunn - 4 months ago 15
iOS Question

Play AVAudioPlayer after delay

I'm trying to play two audio files (click and clack) back to back at an increasing frequency. It works as desired for the first second and then the sounds begin playing at the same time. Any idea what I'm doing wrong here?

static float clickClackDelay = 1.0;

- (void)runClickClackTimer {

clickURL = [[NSBundle mainBundle] URLForResource:@"click" withExtension:@"wav"];
clackURL = [[NSBundle mainBundle] URLForResource:@"clack" withExtension:@"wav"];
avClick = [[AVAudioPlayer alloc] initWithContentsOfURL:clickURL error:nil];
avClack = [[AVAudioPlayer alloc] initWithContentsOfURL:clackURL error:nil];

clickClack = [NSTimer scheduledTimerWithTimeInterval:clickClackDelay
target:self
selector:@selector(runClickClackTimer)
userInfo:nil
repeats:NO];

[avClick play];
sleep(clickClackDelay);
[avClack play];
sleep(clickClackDelay);

NSLog(@"Play sound every %.2f", clickClackDelay);

clickClackDelay -= 0.01;
}

Answer

Firstly define BOOL instance in .h file:

 BOOL play;

Now in add this timer where to need to play sound in delay.

 NSTimer *clickClack = [NSTimer scheduledTimerWithTimeInterval:clickClackDelay
                                              target:self
                                            selector:@selector(runClickClackTimer)
                                            userInfo:nil
                                             repeats:YES];

Its method which will play delay according to clickClackDelay is:

-(void)runClickClackTimer
{
  if(play)
  {
    play = FALSE;
    [avClick play];
  }
  else
  {
    play = TRUE;
    [avClack play];
  }
}
Comments