Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pause and resume buffering of AVPlayer?

Tags:

ios

avplayer

Is it possible to pause and resume buffering of AVPlayer?

like image 447
CharlesFly Avatar asked Mar 10 '23 14:03

CharlesFly


1 Answers

Yes it is possible to some extent!

You can use the playerItem's preferredForwardBufferDuration property to decide how much duration from the current playing time the player should prefetch. But sadly, this is only available from iOS version 10.

Macro to check system version:

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

You can now set how much duration you want to prefetch (in seconds).

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
    NSTimeInterval interval = 1; // set to  0 for default duration.
    _player.currentItem.preferredForwardBufferDuration = interval;
    _player.automaticallyWaitsToMinimizeStalling = YES;

}

automaticallyWaitsToMinimizeStalling is another property which enables the autoplay or autowait feature in avplayer. Because the player is likely to stall frequently if the preferredForwardBufferDuration is set to a smaller duration.

You can also use the playeritem's canUseNetworkResourcesForLiveStreamingWhilePaused property to set if the player should continue or pause buffering when the player is in pause state. This is available from iOS 9 onwards.

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
_player.currentItem.canUseNetworkResourcesForLiveStreamingWhilePaused = NO;
}

The condition check for the system version is very important. You can use the macro mentioned above to do this. Otherwise the app will crash.

UPDATE - swift:

    if #available(iOS 10.0, *) {
            player.currentItem?.preferredForwardBufferDuration = TimeInterval(1)
            player.automaticallyWaitsToMinimizeStalling = true;
    }
like image 147
abhimuralidharan Avatar answered Mar 23 '23 06:03

abhimuralidharan