首先需要创建AVPlayer 这时候要先包含头文件,因为是9.0了,所以不用包含库,直接导入头文件即可
- #import <AVFoundation/AVFoundation.h>
在这里可以把播放器作为成员变量,方便全局使用,当然,也可以不用,我在这里是作为全局变量来使用的,方便内存的管理
- @property (nonatomic,strong) AVPlayer *player;
- @property (nonatomic,strong)AVPlayerLayer *playerLayer;
接着就是创建了
-
- NSString *filePath =[[NSBundle mainBundle]pathForResource:@"flash" ofType:@"mp4"];
- NSURL *sourceMovieURL = [NSURL fileURLWithPath:filePath];
-
- AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
-
- AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
- _player = [AVPlayer playerWithPlayerItem:playerItem];
- _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
-
- _playerLayer.frame = CGRectMake(ScreenWidth/4.4, ScreenHeight/3.3, _coverView.pictureAndAvView.frame.size.width, _coverView.pictureAndAvView.frame.size.height+100);
- _playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
- _playerLayer.backgroundColor = [UIColor blackColor].CGColor;
-
- [_coverView.AirBubble.layer addSublayer:_playerLayer];
- [_player play];
用完是需要注意要对其进行释放:写在你退出的点击事件当中,比如说要pop视图了
- [self.playerLayer removeFromSuperlayer];
-
-
- self.playerLayer=nil;
-
-
- self.player=nil;
搞定!
前两天发现了导致这个问题的根源是没有释放播放器的playeritem 所以还在缓冲 释放播放器时加上两句
[playerItem cancelPendingSeeks];
[playerItem.asset cancelLoading];
停掉playeritem的网络请求释放掉playerintm 就不会再出现这种问题了
[player.currentItem cancelPendingSeeks];
[player.currentItem.asset cancelLoading];
加这两行代码,将正在播放的 item 释放掉