kishan kishan - 2 months ago 25
Objective-C Question

AVPlayer takes long time to start audio play

I am having a music player which streams audio from server, using

AVPlayer
, it plays a audio well, but after completion of an audio , when i click play button for new audio it takes time to start new audio almost 35-40 sec. If anyone can help

Answer

Use observer to know the player state. Using KVO, it's possible to be notified for changes of the player status:

playButton.enabled = NO; player = [AVPlayer playerWithURL:fileURL]; [player addObserver:self forKeyPath:@"status" options:0 context:nil];

This method will be called when the status changes:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                    change:(NSDictionary *)change context:(void *)context {
if (object == player && [keyPath isEqualToString:@"status"]) {
    if (player.status == AVPlayerStatusReadyToPlay) {
        playButton.enabled = YES;
    } else if (player.status == AVPlayerStatusFailed) {
        // something went wrong. player.error should contain some information
    }
}

}

Comments