Thursday, June 6, 2013

AVAudioPlayer playAtTime example in Objective C (iOS).


AVAudioPlayer playAtTime

Plays a sound asynchronously, starting at a specified point in the audio output device’s timeline.

- (BOOL)playAtTime:(NSTimeInterval)time

Parameters
time
The number of seconds to delay playback, relative to the audio output device’s current time. For example, to start playback three seconds into the future from the time you call this method, use code like this:
NSTimeInterval playbackDelay = 3.0; // must be ≥ 0
[myAudioPlayer playAtTime: myAudioPlayer.deviceCurrentTime + playbackDelay];
Important: The value that you provide to the time parameter must be greater than or equal to the value of the audio player’s deviceCurrentTime property.

Return Value
YES on success, or NO on failure.

Discussion of [AVAudioPlayer playAtTime]
Use this method to precisely synchronize the playback of two or more AVAudioPlayer objects. This code snippet shows the recommended way to do this:
AVAudioPlayer playAtTime example.
// Before calling this method, instantiate two AVAudioPlayer objects and
// assign each of them a sound.

- (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
}
To learn about the virtual audio output device’s timeline, read the description for the deviceCurrentTime property.

Calling this method implicitly calls the prepareToPlay method if the audio player is not already prepared to play.


Example of [AVAudioPlayer playAtTime].
   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];

AVAudioPlayer playAtTime example.
- (void)playAtTime:(NSTimeInterval)time withDuration:(NSTimeInterval)duration {
    NSTimeInterval shortStartDelay = 0.01;
    NSTimeInterval now = player.deviceCurrentTime;

    [self.audioPlayer playAtTime:now + shortStartDelay];
    self.stopTimer = [NSTimer scheduledTimerWithTimeInterval:shortStartDelay + duration
                                                      target:self
                                                    selector:@selector(stopPlaying:)
                                                    userInfo:nil
                                                     repeats:NO];
}

- (void)stopPlaying:(NSTimer *)theTimer {
    [self.audioPlayer pause];
}

End of AVAudioPlayer playAtTime example article.