.h文件
//第一步:引用AVFoundation框架,添加播放器屬性 聲明對(duì)象
#import ??<AVFoundation/AVFoundation.h>
//創(chuàng)建對(duì)象
@property (nonatomic,strong)AVPlayer *player;//播放器對(duì)象
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic,strong)AVPlayerItem *currentPlayerItem;
@property (nonatomic,strong)UIView *containerView;
.m
?// 2.創(chuàng)建AVPlayerItem
? ? _currentPlayerItem = [AVPlayerItem playerItemWithURL:url];
? ? //通過(guò)KVO來(lái)觀察status屬性的變化却音,來(lái)獲得播放之前的錯(cuò)誤信息
? ? [_currentPlayerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
context:nil];
? ? // 3.創(chuàng)建AVPlayer
? ? _player = [AVPlayer playerWithPlayerItem:_currentPlayerItem];
?// 4.添加AVPlayerLayer
? ? _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
? ? ? self.playerLayer.backgroundColor = [UIColor blackColor].CGColor;
? ? self.playerLayer.frame = CGRectMake( 0, 104, self.view.frame.size.width, self.view.frame.size.height/2.2);
? ? self.playerLayer.videoGravity = AVLayerVideoGravityResize;
? ? [self.view.layer addSublayer:self.playerLayer];
//此處可以直接播放但是建議在監(jiān)聽(tīng)方法中播放
// [_playerplay];
//監(jiān)聽(tīng)狀態(tài)回調(diào)方法
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:
(NSDictionary *)change context:(void*)context
? ? if([keyPathisEqualToString:@"status"]) {
? ? ? ? //取出status的新值
? ? ? ? AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey]intValue];
? ? ? ? switch(status) {
? ? ? ? ? ? case AVPlayerItemStatusFailed:
//失敗 做相關(guān)失敗操作
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case AVPlayerItemStatusReadyToPlay:
//成功開(kāi)始播放
? ? ? ? ? ? ? ? [_playerplay];
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case AVPlayerItemStatusUnknown:
? ? ? ? ? ? ? ? NSLog(@"視頻資源出現(xiàn)未知錯(cuò)誤");
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? default:
? ? ? ? ? ? ? ? break;
? ? ? ? }
? ? }
? ? //移除監(jiān)聽(tīng)(觀察者)
? ? [objectremoveObserver:self forKeyPath:@"status"];
}