场景:iOS设备在进入AVPlayerViewController时通过AVPlayer自动播放视频。
如何检测AVPlayer何时完成?
答案 0 :(得分:1)
您可以注册以在播放器项目完成播放时收到AVPlayerItemDidPlayToEndTimeNotification
通知。
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.playerItem)
答案 1 :(得分:0)
以防它有助于某人。 我知道它在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.
}
}
答案 2 :(得分:0)
Swift 4.0
NotificationCenter.default.addObserver(self, selector: #selector(self.videoDidEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)