在UICollectionView

时间:2017-06-17 09:59:21

标签: objective-c video-streaming avplayer avplayeritem avplayerlayer

我正在处理一个显示" n"使用AVPlayer&全屏播放的视频数量具有水平滚动的UICollectionView Cell上的AVPlayerLayer类。我在UIScrollView上启用了set paging。因为我只需要播放当前的位置播放器,否则" Previous&下一个"小区玩家应该在"暂停"状态。

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

问题:

(a)中。 "播放&暂停"他们的相关指数没有正常运作。最初" 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"传递网址,我暂停当前玩家" 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"位置值(如当前的视图控制器)。

所以我可以移动那个观点" Top&向下"方向就像在" Facebook messanger应用程序相机访问视图"。

所以当我关闭视图时,我需要释放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库文件中的所有类文件。

最新修改:

#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 中,如前所述,我暂停上次播放的视频

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

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

  - (void)setPauseTheLastViewedPlayerAudio {

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

            [self.lastPlayedVideo mute];

            [self.lastPlayedVideo stopVideoPlay];
        }

        _videoDetailArray = nil;

        [_videoCollectionView reloadData];
    }

因为我应该使用 UIPanGestureRecognizer 来解除用手指从上到下移动的播放器视图。

1 个答案:

答案 0 :(得分:2)

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

让我按步骤解释

  • 我已在视图控制器中声明了一个包含当前视频单元播放器实例的播放器的全局实例。

    @property (nonatomic, strong) InstagramVideoView *sharedVideoPlayer; // Share video player instance
    
  • 为每个单元格创建视频播放器对象。他们还为每个视频播放器保存视频网址。

    - (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]; }

  • 最后一步是在水平集合视图的中心找到当前视频单元。播放我们保存在当前视频单元格中的网址的视频。

    -(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
    

最终结果 - enter image description here

注意 - 为了流畅播放视频,播放器将视频缓存在临时内存中。如果您在以下任何步骤中遇到问题,请与我们联系。