AVPlayer Play, Pause and Buffering issue

2019-05-14 23:54发布

My app plays a streaming video, but when it buffers, the player goes to the pause mode and I have to set it to play mode again manually, I have the following code in my AVPlayer class in order to handle this situation, but it does not work.

In the ViewDidLoad method

[playerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
[playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];

and then, handling the observers using the following methods

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                    change:(NSDictionary *)change context:(void *)context {
if (!player)
{
    return;
}

else if (object == playerItem && [keyPath isEqualToString:@"playbackBufferEmpty"])
{
    if (playerItem.playbackBufferEmpty) {
        //Your code here
    }
}

else if (object == playerItem && [keyPath isEqualToString:@"playbackLikelyToKeepUp"])
{
    if (playerItem.playbackLikelyToKeepUp)
    {
        //Your code here
    }
}

}

is there a another solution for this problem in order to get the player to continues play mode?

1条回答
贼婆χ
2楼-- · 2019-05-15 00:03

This might help,

suppose this is your AVPlayer object
player1 = [AVPlayer playerWithURL:streamURL];

When your video goes in buffer mode then you can pause it and when it done play it again like: In observer method,

if ([object isKindOfClass:[AVPlayerItem class]])
{
    AVPlayerItem *item = (AVPlayerItem *)object;
    //playerItem status value changed?
    if ([keyPath isEqualToString:@"status"])
    {   //yes->check it...

        NSLog(@"STATUS = %d",item.status);
        switch(item.status)
        {
            case AVPlayerItemStatusFailed:
                NSLog(@"player item status failed");
                break;
            case AVPlayerItemStatusReadyToPlay:

                 [playButton setTitle:@"Pause" forState:UIControlStateNormal];
                [player1 play];

                NSLog(@"player item status is ready to play");
                break;
            case AVPlayerItemStatusUnknown:
                NSLog(@"player item status is unknown");
                break;
        }
    }
    else if ([keyPath isEqualToString:@"playbackBufferEmpty"])
    {
        if (item.playbackBufferEmpty)
        {
            [playButton setTitle:@"Play" forState:UIControlStateNormal];
            [player1 pause];
            NSLog(@"player item playback buffer is empty");
        }
    }
}

or you can maintain on button click event. Place one button on your screen to maintain play and pause and addTarget to it with OnClick event.

查看更多
登录 后发表回答