LJPlayer Demo 地址:https://github.com/jasonlee94/LJPlayer
该demo是通过AVFoundation来实现,主要需要设置AVPlayer,AVPlayerItem,AVPlayerLayer这三种属性。
//初始化playerItem
self.playerItem= [AVPlayerItemplayerItemWithURL:self.videoURL];
self.player= [AVPlayerplayerWithPlayerItem:self.playerItem];
//初始化playerLayer
self.playerLayer= [AVPlayerLayerplayerLayerWithPlayer:self.player];
//此处为默认视频填充模式
self.playerLayer.videoGravity=AVLayerVideoGravityResizeAspect;
//添加playerLayer到self.layer
[self.layerinsertSublayer:self.playerLayeratIndex:0];
- (void)setPlayerItem:(AVPlayerItem*)playerItem
{
if(_playerItem== playerItem) {return;}
if(_playerItem) {
[[NSNotificationCenterdefaultCenter]removeObserver:selfname:AVPlayerItemDidPlayToEndTimeNotificationobject:_playerItem];
[_playerItemremoveObserver:selfforKeyPath:@"status"];
[_playerItemremoveObserver:selfforKeyPath:@"loadedTimeRanges"];
[_playerItemremoveObserver:selfforKeyPath:@"playbackBufferEmpty"];
[_playerItemremoveObserver:selfforKeyPath:@"playbackLikelyToKeepUp"];
}
_playerItem= playerItem;
if(playerItem) {
[playerItemaddObserver:selfforKeyPath:@"status"options:NSKeyValueObservingOptionNewcontext:nil];
[playerItemaddObserver:selfforKeyPath:@"loadedTimeRanges"options:NSKeyValueObservingOptionNewcontext:nil];
//缓冲区空了,需要等待数据
[playerItemaddObserver:selfforKeyPath:@"playbackBufferEmpty"options:NSKeyValueObservingOptionNewcontext:nil];
//缓冲区有足够数据可以播放了
[playerItemaddObserver:selfforKeyPath:@"playbackLikelyToKeepUp"options:NSKeyValueObservingOptionNewcontext:nil];
}
}
需要注意的是AVplayer并不能直接addsubView 到你需要显示的View上,那样是看不到视频的,你需要依据你的AVPlayer来创建出AVPlayerLayer,再以 [_yourCustomView.layer insertSublayer:self.playerLayeratIndex:0];这种方式添加到你需要显示的View的layer上。
对于处理接受下来的数据则是在下面这个方法中处理
-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
详细实现过程可以去本人github中下载查看,不足之处欢迎指出