场景:iOS设备在进入AVPlayerViewController时通过AVPlayer自动播放视频。
如何检测AVPlayer何时完成?
当玩家项目完成播放时,您可以注册接收AVPlayerItemDidPlayToEndTimeNotification
通知。
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.playerItem)
以防它帮助某人。我知道它在Obj-C中,但我不得不将其添加到一些旧代码中;)
- (void)setupVideo {
NSString *stringVideoName = @"myVideo.mp4";
NSString *stringVideoPath = [[NSBundle mainBundle] pathForResource:stringVideoName ofType:nil];
NSURL *urlVideoFile = [NSURL fileURLWithPath:stringVideoPath];
_playerViewController = [[AVPlayerViewController alloc] init];
_playerViewController.player = [AVPlayer playerWithURL:urlVideoFile];
_playerViewController.view.frame = self.videoView.bounds;
_playerViewController.showsPlaybackControls = YES;
// Identify when the player time position jumps.
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(playerItemTimeJumped:) name:AVPlayerItemTimeJumpedNotification object:_playerViewController.player.currentItem];
[self.videoView addSubview:_playerViewController.view];
self.videoView.autoresizesSubviews = YES;
}
- (void)playerItemTimeJumped:(NSNotification*)notification {
AVPlayerItem *playerItem = notification.object;
if (playerItem.status == AVPlayerItemStatusReadyToPlay) {
[NSNotificationCenter.defaultCenter removeObserver:self name:AVPlayerItemTimeJumpedNotification object:notification.object];
// The video play button has been pressed only once. Tell someone about it.
}
}
Swift 4.0
NotificationCenter.default.addObserver(self, selector: #selector(self.videoDidEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)