我正在使用带有分页功能的UICollectionView
并在每个单元格上添加AVPlayer
以使用URL
播放视频,但我的收藏视图给出了一种奇怪的行为。当它加载第一个单元格并且视频开始播放时它很好但是当我滑动并加载下一个单元格时,两个视频一起播放,而我希望前一个视频停止播放。我尝试了很多东西来解决这个问题,但没有任何工作,有人请建议我使用这个。我添加AVPlayer
的自定义单元格类代码如下:
[self.avPlayer pause];
self.avPlayer = nil;
[self.avLPlayer removeFromSuperlayer];
CGRect videoRect;
videoRect = CGRectMake(0,0,[[UIScreen mainScreen]bounds].size.width,[[UIScreen mainScreen]bounds].size.height);
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[indicator startAnimating];
[indicator bringSubviewToFront:_viewForShowVideo];
UIWindow* currentWindow = [UIApplication sharedApplication].keyWindow;
indicator.frame = CGRectMake(currentWindow.frame.size.width/2, _viewForShowVideo.frame.size.height/2, 20, 20);
[_viewForShowVideo addSubview:indicator];
self.avPlayerItem = [AVPlayerItem playerItemWithURL:Url];
self.avPlayer = [AVPlayer playerWithPlayerItem:self.avPlayerItem];
self.avLPlayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
[_avLPlayer setFrame:videoRect];
[_avLPlayer setBackgroundColor:[UIColor blackColor].CGColor] ;
[_avLPlayer setVideoGravity:AVLayerVideoGravityResizeAspect];
_avLPlayer.opacity = 1;
_avPlayer.allowsExternalPlayback = NO;
[_avPlayer setMuted:NO];
_avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
[[AVAudioSession sharedInstance]setCategory: AVAudioSessionCategoryPlayback error: nil];
[_viewForShowVideo.layer addSublayer:_avLPlayer];
[_avPlayer play];
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnPlayer:)];
[_viewForShowVideo addGestureRecognizer:tgr];
[_viewForShowVideo setBackgroundColor:[UIColor greenColor]];