使用 AVFoundation AVPlayer 无法按预期从服务器循环播放

Looping playback from server not working as expected with AVFoundation AVPlayer

从设备本地播放 .mp4 时,媒体按预期循环播放。当媒体来自服务器时,视频停止播放时不会触发任何通知

AVPlayer *avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:@"http://www.someurl.com/someMedia.mp4"]];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
avPlayerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self.view.layer addSublayer:avPlayerLayer];

[avPlayer play];


// Loop video
avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(playerItemDidReachEnd:)
                                             name:AVPlayerItemDidPlayToEndTimeNotification
                                           object:[avPlayer currentItem]];




- (void)playerItemDidReachEnd:(NSNotification *)notification {

    NSLog(@"Video ended");

    AVPlayerItem *p = [notification object];
    [p seekToTime:kCMTimeZero];
}

选中Looping a video with AVFoundation AVPlayer? and How do I loop a video with AVFoundation without unwanted pauses at the end?

更新

感谢 ChrisH,创建了一个延迟以允许在观察播放器正确播放视频之前从服务器加载视频

double delayInSeconds = 7.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

        avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(playerItemDidReachEnd:)
                                                     name:AVPlayerItemDidPlayToEndTimeNotification
                                                   object:[avPlayer currentItem]];



    });

远程 mp4 未触发通知的原因是您在创建播放器后立即观察来自 AVPlayer 实例的 currentItem 的通知,而 currentItemnil 直到从服务器加载内容。

推荐的处理方法是观察玩家实例的 status 属性,一旦该状态等于 AVPlayerStatusReadyToPlay,您就可以开始观察来自 [=11] 的通知=]. this SO answer

中有很好的解释和示例代码