当使用AVPlayer从互联网流式传输视频时,UI正在冻结

时间:2014-08-19 15:22:27

标签: ios avplayer

我正在iOS平台中实现Media Player。当使用AVPlayer从互联网流式传输视频时,我遇到了UI Freezing的问题。注意:我没有使用AVAudioPlayer,AVQueuePlayer。以下是播放媒体的代码:UI Freeze仅在开始流媒体时发生。

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];

}

我提到了以下链接: AVPlayer "freezes" the app at the start of buffering an audio stream 但该链接建议 AVQueuePlayer 。但我的要求是在 AVPlayer

中进行

1 个答案:

答案 0 :(得分:2)

当您开始播放视频时尚未下载任何数据时,AVPlayer类有一个名为prerollAtRate:completionHandler的方法,该方法从项目的当前播放时间开始加载数据,然后在完成加载时调用completionHandler尝试。

__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]; 

        });
    }

}];