colindunn
colindunn

Reputation: 3163

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;
}

Upvotes: 0

Views: 1030

Answers (2)

Paresh Navadiya
Paresh Navadiya

Reputation: 38239

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];
  }
}

Upvotes: 1

David Brunow
David Brunow

Reputation: 1299

The first sleep timer and the NSTimer will both delay for the same amount of time, 1 second, therefore calling

[avClack play];

in the first instance of runClickClackTimer at the same time as

[avClick play];

in the second instance of runClickClackTimer.

I would set up two separate NSTimers that call two separate functions, perhaps runClickTimer and runClackTimer.

Upvotes: 0

Related Questions