How to play multiple videos smoothly in iOS in UICollectionView?

元气小坏坏 提交于 2019-12-07 10:48:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!