3

I am implementing Media Player in iOS Platform. I have a problem with UI Freezing, when streaming the videos from the internet using AVPlayer. Note: I'm not using AVAudioPlayer, AVQueuePlayer. Here following code for playing the media: UI Freeze is occurring only start Streaming.

if(_player.rate!=0.0)
    {
        [_player pause];
        [ad.player.playerLayer removeFromSuperlayer];
        [_player replaceCurrentItemWithPlayerItem:[ AVPlayerItem playerItemWithURL:_tempURL]];
    }
    else
    {
        _player = [_player initWithURL:mediaURL];

   ad.player.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    ad.player.playerLayer.frame=ad.player.bounds;
    ad.player.playerLayer.frame=CGRectMake(0, 0, 320, 150);
    [ad.player.playerLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    _player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
    ad.player.playerLayer.needsDisplayOnBoundsChange = YES;
    [ad.player.layer addSublayer:ad.player.playerLayer];

    [_player play];

}

I referred the following Link: AVPlayer "freezes" the app at the start of buffering an audio stream But that link suggested for AVQueuePlayer. But my Requirement is to do in AVPlayer

Community
  • 1
  • 1
iTag
  • 409
  • 3
  • 19
  • I updated the answer in the referenced link with a comment explaining how it worked for me when using just AVPlayer: http://stackoverflow.com/a/11793904/1735721. Essentially: follow the answer but use replaceCurrentItemWithPlayerItem in the completion handler. – DennisWelu Oct 23 '15 at 19:09

1 Answers1

4

When you start playing the video it hasn't downloaded any data yet, AVPlayer class has a method called prerollAtRate:completionHandler which loads data starting at the item’s current playback time, which then calls a completionHandler whens its finishes the load attempt.

__weak typeof(self) weakSelf = self;  
[self prerollAtRate:0.0 completionHandler:^(BOOL finished) {
    NSLog(@"ready: %d", finished);

    // if ready call the play method
    if (finished) {
        dispatch_async(dispatch_get_main_queue(), ^{
           // call UI on main thread
           [weakSelf.player play]; 

        });
    }

}];
Shams Ahmed
  • 4,498
  • 4
  • 21
  • 27