首页 文章

在UICollectionView上使用AVPlayer和AVPlayerLayer显示多个视频

提问于
浏览
2

我正在使用带有水平滚动的UICollectionView Cell上的AVPlayer和AVPlayerLayer类在全屏幕上显示“n”个视频的应用程序 . 我在UIScrollView上启用了set paging . 因为我只需要播放当前位置播放器,否则“上一个和下一个”小区播放器应该处于“暂停”状态 .

我正在以url格式获取视频 . 所以最初我需要下载,之后它将开始播放 . 因此,每个人都不需要从URL下载视频 . 所以我决定将下载的视频缓存在本地 . 所以我下载并将其存储在本地文件中 . 然后我从本地加载视频如果它存在于本地文件中 .

问题:

(一个) . “播放和暂停”在相关索引上无法正常工作 . 最初“0”指数被播放 . 当我滚动到下一个索引此时应该正在播放当前的索引播放器时,下一个索引播放器应该处于“暂停”状态 . 它没有正确同步 .

(b)中 . 我可以看到之前的播放器视频片段,直到下一个播放器开始播放 .

(C) . 所有观看的音频同时在后台播放以及释放播放器时也是如此 . (我的意思是,我可以在驳回一些观点或查看控制器之后听到)

(d)需要保持内存泄漏问题 .

我在下面尝试了源代码的方式,

- (void)setVideoLoading:(NSString *)videoUrl{

    NSString *urlString = videoUrl;

    SHAREDATA.videoUrl = [NSURL URLWithString:urlString];

    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:SHAREDATA.videoUrl options:nil];

    NSArray *requestedKeys = @[@"playable"];

    //Tells the asset to load the values of any of the specified keys that are not already loaded.
    [asset loadValuesAsynchronouslyForKeys:requestedKeys completionHandler:^{

        dispatch_async(dispatch_get_main_queue(), ^{

            AVPlayerItem *item = [AVPlayerItem playerItemWithAsset: asset];

            if (self.avPlayer)
            {
                /* Remove existing player item key value observers and notifications. */

                [self.avPlayer removeObserver:self forKeyPath:@"status" context:nil];

                [[NSNotificationCenter defaultCenter] removeObserver:self
                                                                name:AVPlayerItemDidPlayToEndTimeNotification
                                                              object:self.avPlayer.currentItem];
            }

            self.avPlayer = [AVPlayer playerWithPlayerItem:item];

            self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];

            if (_typeOfContentMode == UIViewContentModeScaleAspectFit) {

                self.avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
            }
            else if (_typeOfContentMode == UIViewContentModeScaleAspectFill)
            {
                self.avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
            }


            self.avPlayerLayer.frame = CGRectMake(0, 0, _videoBackgroundView.frame.size.width, _videoBackgroundView.frame.size.height);

            [_videoBackgroundView.layer addSublayer:self.avPlayerLayer];

            self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;

            self.avPlayer.muted = NO;

            [self.avPlayer addObserver:self
                                forKeyPath:@"status"
                                   options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                                   context:nil];
        });
    }];

下面是KVO方法 .

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {

    if (object == self.avPlayer && [keyPath isEqualToString:@"status"]) {

        if (self.avPlayer.status == AVPlayerStatusReadyToPlay) {

            [_videoProgressView setProgress:0 animated:NO];

            [self setVideoPlayEnabled];

            [self setAutoUpdateTimer];

            [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:[self.avPlayer currentItem]];

            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(playerItemDidReachEnd:)
                                                         name:AVPlayerItemDidPlayToEndTimeNotification
                                                       object:[self.avPlayer currentItem]];
        }
        else if (self.avPlayer.status == AVPlayerStatusFailed ||
                 self.avPlayer.status == AVPlayerStatusUnknown) {

            [SVProgressHUD dismiss];

            if (self.avPlayer.rate>0 && !self.avPlayer.error)
            {
                [self.avPlayer setRate:0.0];

                [self.avPlayer pause];
            }
        }
    }
}

- (void)playerItemDidReachEnd:(NSNotification *)notification {

    [SVProgressHUD dismiss];

    AVPlayerItem *p = [notification object];

    [p seekToTime:kCMTimeZero completionHandler:^(BOOL finished)
     {             
         [self.avPlayer play];
     }];
}

我从“cellForItemAtIndexPath”传递url,我将当前播放器暂停在“didEndDisplayingCell”上 .

然后在“scrollViewDidEndDecelerating”中,我刚检查了我的customCell类的其他全局实例(在全局变量上声明)并暂停该单元格当前播放器 .

但主要目的是scrollViewDidEndDecelerating,我正在获得当前可见的单元格 .

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.lastPlayingCell) {

        [self.lastPlayingCell.avPlayer pause];
    }

    // Play/Pause Video
    CGRect visibleRect = (CGRect){.origin = self.videoCollectionView.contentOffset, .size = self.videoCollectionView.bounds.size};

    CGPoint visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect));

    _visibleIndexPath = [self.videoCollectionView indexPathForItemAtPoint:visiblePoint];

    DetailsCollectionCell *cell = (DetailsCollectionCell *)[self.videoCollectionView cellForItemAtIndexPath:_visibleIndexPath];

    if (![cell isEqual: self.lastPlayingCell]) {

        [self.avPlayer play];

        self.lastPlayingCell = cell;//assigned to current visible cell to lastplayingcell instance. 
    }
}

我在这里告知一件事,我只是将AVPlayer显示为UIView类的子视图 . 当我点击视频拇指图像(UITableView上发布的视频信息列表的前一个视图)时,我的意思是UITable选择功能,我只是显示UIView移动它的“Y”位置值(就像现在的视图控制器一样) .

所以我可以在“Facebook messanger app camera access view”中移动该视图“Top&down”方向 .

因此,当我关闭视图时,我需要释放AVPlayer,在所有已观看视频的背景上停止音频并删除已注册的观察者类,如下所示 .

- (void)setRemoveRegisteredObserversAndPlayerRelatedElements
{
    [self.avPlayer removeObserver:self forKeyPath:@"status" context:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:[self.avPlayer currentItem]];

    [self.avPlayerLayer.player pause];

    [self.avPlayer pause];

    self.avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:@""]];

    [self.avPlayerLayer removeFromSuperlayer];

    self.avPlayerLayer.player = nil;

    self.avPlayerLayer = nil;

    self.avPlayer = nil;
}

任何想法解决这些问题并在当前索引上顺利播放视频,停止音频并处理内存泄漏 .

任何人分享或提出一些建议来实现这一目标 .

cellForItemAtIndexPath

- (UICollectionViewCell *) collectionView: (UICollectionView *) collectionView cellForItemAtIndexPath: (NSIndexPath *) indexPath
{
    videoDetailsCollectionCell *videoDetailCell = [collectionView dequeueReusableCellWithReuseIdentifier:kVideoDetailsCollectionCell forIndexPath:indexPath];

    NSDictionary *publishedVideoObject = [self.videoDetailArray objectAtIndex:indexPath.row];

    [videoDetailCell loadVideoURL:publishedVideoObject];

    return videoDetailCell;
}

我已经添加了ZOWVideoPlayer库文件中的所有类文件 .

Latest Edit:

#pragma mark - Load video url for their current index cell
- (videoDetailsCollectionCell *)videoCellFor:(UICollectionView *)collectionView withIndex:(NSIndexPath *)indexPath
{
    videoDetailsCollectionCell * videoCell = [collectionView dequeueReusableCellWithReuseIdentifier:kCustomVideoCell forIndexPath:indexPath];

    //[videoCell.videoView.videoPlayer resume];

    return videoCell;
}

在CellForItemAtIndexPath方法中

NSDictionary *publicationObject = [videoDetailArray objectAtIndex:indexPath.row];

    videoDetailsCollectionCell * cell = [self videoCellFor:collectionView withIndex:indexPath];

    cell.mediaUrl = [NSString replaceEmptyStringInsteadOfNull:[NSString stringWithFormat:@"%@",publicationObject.video]];

    return cell;

然后在 scrollViewDidScroll ,如前所述,我是 Pause last played videos .

然后在 scrollViewDidEndDecelerating 我跟随下面的答案部分,除了使用 UICollectionView 而不是 IndexedCollectionView 类来检索页面计数信息 .

最后我停止了所有播放的视频如下,

- (void)setPauseTheLastViewedPlayerAudio {

        // Pause last played videos
        if (self.lastPlayedVideo) {

            [self.lastPlayedVideo mute];

            [self.lastPlayedVideo stopVideoPlay];
        }

        _videoDetailArray = nil;

        [_videoCollectionView reloadData];
    }

因为我应该使用 UIPanGestureRecognizer 来解除用手指从上到下移动的玩家视图 .

1 回答

  • 2

    前段时间我正在努力解决同样的问题 . 我解决这个问题的方法与你的不同 .

    让我逐步解释

    • 我已在视图控制器中声明了一个包含当前视频单元播放器实例的播放器的全局实例 .
    @property (nonatomic, strong) InstagramVideoView *sharedVideoPlayer; // Share video player instance
    
    • 为每个单元格创建视频播放器对象,并且它们还保存每个视频播放器的视频URL .
    - (CommonVideoCollectionViewCell *)videoCellFor:(UICollectionView *)collectionView withIndex:(NSIndexPath *)indexPath {
        CommonVideoCollectionViewCell *videoCell = [collectionView dequeueReusableCellWithReuseIdentifier:VideoCollectionViewCellIdentifier forIndexPath:indexPath];
        return videoCell;
    }
    -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
      CommonVideoCollectionViewCell *cell = [self videoCellFor:collectionView withIndex:indexPath];
      cell.mediaUrl = tempMedia.media;
      return cell;
    }
    
    • 每次用户尝试滚动收集单元格时,都会暂停视频播放器的全局实例中的视频 . 这解决了细胞的闪烁问题 .

    // Pause last played videos if (self.sharedVideoPlayer) { [self.sharedVideoPlayer pause]; [self.sharedVideoPlayer mute]; }

    • 最后一步是在水平集合视图的中心找到当前视频单元,并从我们保存在当前视频单元格中的URL播放视频 .
    -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
      if ([scrollView isKindOfClass:[UITableView class]]) {
        return;
      }
    
    IndexedCollectionView *pageContentCollectionView = (IndexedCollectionView *)scrollView;
    CGPoint centerPoint = CGPointMake(pageContentCollectionView.center.x + pageContentCollectionView.contentOffset.x,
                                  pageContentCollectionView.center.y + pageContentCollectionView.contentOffset.y);
    
    NSIndexPath *centerCellIndexPath = [pageContentCollectionView indexPathForItemAtPoint:centerPoint];
    NSArray *visibleCells = [pageContentCollectionView visibleCells];
    // Get cell for index & pause video playback
    UICollectionViewCell *cell = [pageContentCollectionView cellForItemAtIndexPath:centerCellIndexPath];
    
    for (UICollectionViewCell *tempCell in visibleCells) {
    if ([tempCell isKindOfClass:[CommonVideoCollectionViewCell class]]) {
        CommonVideoCollectionViewCell *videoCell = (CommonVideoCollectionViewCell *)tempCell;
        InstagramVideoView *videoPlayer = [videoCell videoView];
        // Pause & mute all the video player instance
        [videoCell.videoView setHidden:YES];
        [videoCell.placeholderImageView setHidden:NO];
        [videoPlayer pause];
        [videoPlayer mute];
        // Check if the central cell is present
        if (tempCell == cell) {
            self.sharedVideoPlayer = videoPlayer;// Save played video player instance
            [self.sharedVideoPlayer playVideoWithURL:[NSURL URLWithString:[(CommonVideoCollectionViewCell *)tempCell mediaUrl]]];
            [videoCell.videoView setHidden:NO];
            [videoCell.placeholderImageView setHidden:YES];
            [videoPlayer resume]; // resume video playback
            [videoPlayer mute];
        }
      }
     }
    }
    

    CommonVideoCollectionViewCell

    #import<UIKit/UIKit.h>
    #import "InstagramVideoView.h"
    @interface CommonVideoCollectionViewCell : UICollectionViewCell
    @property (weak, nonatomic) IBOutlet InstagramVideoView *videoView;
    @property (weak, nonatomic) IBOutlet UIImageView *placeholderImageView;
    // Set media url
    @property (strong, nonatomic) NSString *mediaUrl;
    @end
    

    End result -
    enter image description here

    Note - For smooth video playing, the player cache the video in temp memory. let me know if you have issue in any of the following steps.

相关问题