Blue
Blue

Reputation: 2370

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

Upvotes: 0

Views: 1324

Answers (2)

Rufus Mall
Rufus Mall

Reputation: 589

Yeah what he said ^ The play at time will schedule both players to start at that time (sometime in the future).

To make it obvious, you can set "shortStartDelay" to 2 seconds and you will see there will be a two second pause before both items start playing.

Another tip to keep in mind here are that when you play/pause AVAudioPlayer they dont actually STOP at exactly the same time. So when you want to resume, you should also sync the audio tracks.

Swift example:

 let currentDeviceTime = firstPlayer.deviceCurrentTime
                        let trackTime = firstPlayer.currentTime
                        players.forEach {
                            $0.currentTime = trackTime
                            $0.play(atTime: currentDeviceTime + 0.1)
                        }

Where players is a list of AVAudioPlayers and firstPlayer is the first item in the array.

Notice how I am also resetting the "currentTime" which is how many seconds into the audio track you want to keep playing. Otherwise every time the user plays/pauses the track they drift out of sync!

Upvotes: 0

Matthias
Matthias

Reputation: 1026

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

Upvotes: 3

Related Questions