创建一个视频播放器,播放准备好的视频
NSString *url = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp4"];
self.mp4Item = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:url]];
[self.mp4Item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
self.player = [[AVPlayer alloc] initWithPlayerItem:self.mp4Item];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerbacDidPlayEndTime) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
playerLayer.position = self.view.center;
playerLayer.bounds = CGRectMake(0, 0, JMScreenWidth, JMScreenHeight);
[self.view.layer addSublayer:playerLayer];```
然后在视频上添加需要的控件,需要注意的是,添加的控件需要在视频之后添加
这里面添加了KVC观察item的状态,根据状态确定操作,这是observerValuesForKeyPath:ofObject:change:context:
if ([keyPath isEqualToString:@"status"]) {
if (self.mp4Item.status == AVPlayerItemStatusReadyToPlay) {
[self.player play];
}
}
当完成播放的时候需要重新设置播放时间
[self.player seekToTime:CMTimeMake(0, 1)];
[self.player play];