问题
I want to play multiple videos in infinite loop in my collection view.
Each Video represent a cell.
I am using ALAsset.
I am playing this using AVPLayer but it's not loading and playing smoothly. Any Suggestions.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
CGRect attachmentFrame = CGRectMake(2, 2, cell.frame.size.width-4, cell.frame.size.height-4);
ALAsset *asset = self.assets[indexPath.row];
UIView* subView;
if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo]) {
// asset is a video
avPlayer = [[AVPlayer alloc] initWithURL:[[asset defaultRepresentation] url]];
avPlayer.muted = YES;
avPlayerLayer =[AVPlayerLayer playerLayerWithPlayer:avPlayer];
[avPlayerLayer setFrame:CGRectMake(0, 0, cell.frame.size.width-4, cell.frame.size.height-4)];
subView = [[UIView alloc]initWithFrame:attachmentFrame];
[subView.layer addSublayer:avPlayerLayer];
[[cell.contentView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
[cell.contentView addSubview:subView];
[avPlayer seekToTime:kCMTimeZero];
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[avPlayer play];
avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:[avPlayer currentItem]];
}
}
- (void)playerItemDidReachEnd:(NSNotification *)notification {
AVPlayerItem *p = [notification object];
[p seekToTime:kCMTimeZero];
}
I also tried MPMoviePlayerController but using movie player you can play only one video in loop. Any other suggestion related to buffered video or thumbnail images. I don't want to play sound in video.
回答1:
AVPlayer
able to play multiple video in app very smoothly but you need to manage cell for collection view because In your code, when your cell reload, your newAVPlayer
object create for same video which create issue.
So you need to implement such an mechanism by which can achieve to create single AVPlayer object for one video. One suggestion is managing pool for AVPlayer
objects.
Thanks
来源:https://stackoverflow.com/questions/31333375/how-to-play-multiple-videos-smoothly-in-ios-in-uicollectionview