Changing playerItem of AVPlayer in UITableView

前端 未结 3 1888
我寻月下人不归
我寻月下人不归 2020-12-23 19:47

I have a UITableView containing a number of videos to play when scrolling. As the cells in the tableView are being re-used, I only instantiate one AVPlaye

3条回答
  •  无人及你
    2020-12-23 20:49

    If you do some basic level of profiling, I think you can narrow down the problem. For me, I had a similar issue where replaceCurrentItemWithPlayerItem was blocking the UI thread. I resolved it by examining my code to find out which line was taking time. For me the AVAsset loading was taking time. So I used the loadValuesAsynchronouslyForKeys method of AVAsset to resolve my issue.

    Hence can you try the following:

    -(void)initializeNewObject:(CustomObject*)o
    {
        //If this cell is being dequeued/re-used, its player might still be playing the old file
        [self.player pause];
        self.currentObject = o;
        /*
        //Setting text-variables for title etc. Removed from this post, but by commenting them out in the code, nothing improves.
        */
    
        //Replace the old playerItem in the cell's player
        NSURL *url = [NSURL URLWithString:self.currentObject.url];
        AVAsset *newAsset = [AVAsset assetWithURL:url];
        [newAsset loadValuesAsynchronouslyForKeys:@[@"duration"] completionHandler:^{
            AVPlayerItem *newItem = [AVPlayerItem playerItemWithAsset:newAsset];
            [self.player replaceCurrentItemWithPlayerItem:newItem];
        }];
    
    
        //The last line above, replaceCurrentItemWithPlayerItem:, is the 'bad guy'.
        //When commenting that one out, all lag is gone (of course, no videos will be playing either)
        //The lag still occurs even if I never call [self.player play], which leads me
        //to believe that nothing after this function can cause the lag
    
        self.isPlaying = NO;
    }
    

提交回复
热议问题