Search code examples
iphoneobjective-csynchronizationavaudioplayer

Synchronize the playback of two or more AVAudioPlayer in Iphone


I need to play 2 sounds with 2 AVAudioPlayer objects at the same exact time... so I found this example on Apple AVAudioPlayer Class Reference (https://developer.apple.com/library/mac/#documentation/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html):

- (void) startSynchronizedPlayback {



NSTimeInterval shortStartDelay = 0.01;            // seconds

NSTimeInterval now = player.deviceCurrentTime;



[player       playAtTime: now + shortStartDelay];

[secondPlayer playAtTime: now + shortStartDelay];



// Here, update state and user interface for each player, as appropriate

}

What I don't understand is: why also the secondPlayer has the shorStartDelay? Shouldn't it be without? I thought the first Player needed a 0.1 sec delay as it is called before the second Player... but in this code the 2 players have the delay... Anyone can explain me if that is right and why? Thanks a lot Massy


Solution

  • If you only use the play method ([firstPlayer play];), firstPlayer will start before the second one as it will receive the call before.

    If you set no delay ([firstPlayer playAtTime:now];), the firstPlayer will also start before de second one because firstPlayer will check the time at which it is supposed to start, and will see that it's already passed. Thus, it will have the same behaviour as when you use only the play method.

    The delay is here to ensure that the two players start at the same time. It is supposed to be long enough to ensure that the two players receive the call before the 'now+delay' time has passed.

    I don't know if I'm clear (English is not my native langage). I can try to be more clear if you have questions