Wednesday, June 5, 2013

AVAudioPlayer deviceCurrentTime example in Objective C (iOS).

AVAudioPlayer deviceCurrentTime

The time value, in seconds, of the audio output device. (read-only)

@property(readonly) NSTimeInterval deviceCurrentTime

Discussion of [AVAudioPlayer deviceCurrentTime]
The value of this property increases monotonically while an audio player is playing or paused.

If more than one audio player is connected to the audio output device, device time continues incrementing as long as at least one of the players is playing or paused.

If the audio output device has no connected audio players that are either playing or paused, device time reverts to 0.[AVAudioPlayer deviceCurrentTime]

Use this property to indicate “now” when calling the playAtTime: instance method. By configuring multiple audio players to play at a specified offset from deviceCurrentTime, you can perform precise synchronization—as described in the discussion for that method.

AVAudioPlayer deviceCurrentTime example.
   NSTimeInterval shortStartDelay = 0.5;            // seconds
    NSTimeInterval now = player.deviceCurrentTime;

    [player playAtTime:now + shortStartDelay];  //these players are instances of AVAudioPlayer
    [player2 playAtTime:now + shortStartDelay];
    [player3 playAtTime:now + shortStartDelay];

Example of [AVAudioPlayer deviceCurrentTime].
- (IBAction)valueChanged:(id)sender {
    UISwitch *aSwitch = (UISwitch*)sender;
    if ( aSwitch.on ) {
        NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"horn"

        NSURL *fileURL = [NSURL fileURLWithPath:soundFilePath];

        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL

        [audioPlayer playAtTime:(audioPlayer.deviceCurrentTime + 3)];
    } else {
        [audioPlayer stop];

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    [self.theSwitch setOn:NO animated:YES];

    [player release];

AVAudioPlayer deviceCurrentTime example.
- (void) startSynchronizedPlayback {

    NSTimeInterval shortStartDelay = 0.01;            // seconds
    NSTimeInterval now = player.deviceCurrentTime;

    [player       playAtTime: now + shortStartDelay];
    [secondPlayer playAtTime: now + shortStartDelay + player.duration];

End of AVAudioPlayer deviceCurrentTime example article.