views:

206

answers:

1

So, I'm finishing up an iPhone App.

I have the following code in place to play the file:

while(![player isPlaying]) {
  totalSoundDuration = soundDuration + 0.5; //Gives a half second break between sounds
  sleep(totalSoundDuration); //Don't play next sound until the previous sound has finished
  [player play]; //Play sound
  NSLog(@" \n Sound Finished Playing \n"); //Output to console
}

For some reason, the sound plays once then the code loops and it outputs the following:

Sound Finished Playing
Sound Finished Playing
Sound Finished Playing
etc...

This just repeats forever, I don't suppose any of you lovely people can fathom what could be the boggle?

Cheers!

+3  A: 

I am not exactly sure what's wrong with your code, it could be that [player play] is an asyncronous call, but you loop forever without letting the player to actually start playing or realizing that it is actually playing. I don't recommend using sleep in any iPhone applications, because the whole model is based on asynchronous events.

I did not test this code or even compile it, but I hope you get the idea from it.

- (void) startPlayingAgain:(NSTimer *)timer
{
    AVAudioPlayer *player = timer.userInfo;

    [player play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player 
                       successfully:(BOOL)flag
{
  NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5
                            target:self
                            selector:@selector(startPlayingAgain:)
                            userInfo:player
                            repeats:NO];
}

- (void)startPlaying:(NSString *)url
{
    AVAudioPlayer *player = [[AVAudioPlayer alloc] 
                                initWithContentsOfURL:url error:NULL];

    player.delegate = self;

    [player play];
}

Tuomas Pelkonen
Do you mean like: -(void)audioPlayerDidFinishPlaying:(nsstring *)audioPlayer finished:(BOOL *)finished context:(void *)context { } - Any chance you could pop a quick example for me please? :)
Neurofluxation
Sure, give me a second...
Tuomas Pelkonen
Thanks very much!
Neurofluxation