Handle streaming events with AVPlayer

Quentin Hayot picture Quentin Hayot · Jun 16, 2011 · Viewed 24k times · Source

I'm building an app which plays an audio stream (from a webradio).

I'm using AVPlayer for it.

  1. I'd like to know how you would handle AVPlayer's "buffering" when the connection is slow or when the user just clicked "play". I want to detect that AVPlayer is "buffering" to display an UIActivityIndicatorView.

  2. Same question while running in the background. What should I do if buffering in this case?

Answer

sciasxp picture sciasxp · Aug 26, 2011

For the first question

You can refer to my answer on this topic ios avplayer trigger streaming is out of buffer

For the second

Here is how I solved this same problem:

Inside where you handle the event for buffer empty add this code:

    if (object == playerItem && [keyPath isEqualToString:@"playbackBufferEmpty"])
    {
        if (playerItem.playbackBufferEmpty) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"message" object:@"Buffering..."];
            
            if([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
            {
                task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) {
                }];
            }
        }
    }

Now you will have to stop this background task after your buffer is ready to go again:

if (object == playerItem && [keyPath isEqualToString:@"playbackLikelyToKeepUp"])
{
    if (playerItem.playbackLikelyToKeepUp)
    {
        [player play];
        
        if([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
        {
            [[UIApplication sharedApplication] endBackgroundTask:task];
            task = 0;
        }
    }
}

ps: task is declared on my .h file as UIBackgroundTaskIdentifier task;