2015-07-21 75 views
1

我在桌面視圖中使用AVPlayer。我想要開始視頻播放,在滾動表格視圖時停止播放視頻。告訴我有什麼可行的方法來做到這一點?AVPlayer恢復能力

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
static NSString *tableIdentifier = @"tableIdentifier"; 
CustomTableCell *cell = [self.videoTableView dequeueReusableCellWithIdentifier:tableIdentifier]; 
if (cell == nil) { 
    cell = [[[NSBundle mainBundle]loadNibNamed:@"VideoCell" owner:self options:nil]objectAtIndex:0]; 
} 
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
dispatch_async(queue, ^{ 
    AVAsset *avAssert = [AVAsset assetWithURL:[NSURL URLWithString:@"url"]]; 
    cell.playerItem =[[AVPlayerItem alloc]initWithAsset:avAssert]; 
    dispatch_sync(dispatch_get_main_queue(), ^{ 
     if (!cell.avPlayer) { 
      cell.avPlayer = [AVPlayer playerWithPlayerItem:cell.playerItem]; 
     }else{ 
      [cell.avPlayer replaceCurrentItemWithPlayerItem:cell.playerItem]; 
     } 
     if (!cell.avPlayerLayer) { 
      cell.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:cell.avPlayer]; 
      cell.avPlayerLayer.frame = cell.videoPlayerView.layer.bounds; 
      cell.avPlayerLayer.videoGravity = AVLayerVideoGravityResize; 
      [cell.videoPlayerView.layer addSublayer: cell.avPlayerLayer]; 
      if (indexPath.row == 0) { 
       cell.avPlayer.muted = NO; 
       [cell.avPlayer play]; 
      } 
     } 
    }); 
}); 
return cell; 

}

+1

您必須保留一系列視頻持續時間,以便在該視頻暫停視頻時再次滾動至相同視頻,首先檢查開始播放視頻持續時間在陣列 –

+0

目前,我正在做你說的。問題是我重複使用細胞。 somtimes它不需要正確的AVPlayerItem當前time.i'll試着讓你知道,謝謝。 – PramukaD

+0

粘貼一些代碼 –

回答

0

這裏的蘋果是如何做到這樣的事情在一個示例應用程序(我這樣做是不同的):

/* When the app goes to the background, save the media url and time values 
to the application preferences. */ 
- (void)applicationDidEnterBackground:(UIApplication*)application 
{ 
    if (self.playbackViewController) 
    { 
     NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; 
     NSURL* URL = [self.playbackViewController URL]; 

     if (URL) 
     { 
      NSTimeInterval time = CMTimeGetSeconds([[self.playbackViewController player] currentTime]); 

      [defaults setURL:URL forKey:AVPlayerDemoContentURLUserDefaultsKey]; 
      [defaults setDouble:time forKey:AVPlayerDemoContentTimeUserDefaultsKey]; 
     } 
     else 
     { 
      [defaults removeObjectForKey:AVPlayerDemoContentURLUserDefaultsKey]; 
      [defaults removeObjectForKey:AVPlayerDemoContentTimeUserDefaultsKey]; 
     } 

     [defaults synchronize]; 
    } 
} 

在任何一種(或兩者)appDidFinishLaunching或appDidEnterForeground方法:

NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; 

    /* Restore saved media time value from defaults system. */ 
    [[self.playbackViewController player] seekToTime:CMTimeMakeWithSeconds([defaults doubleForKey:AVPlayerDemoContentTimeUserDefaultsKey], NSEC_PER_SEC)]; 
} 

return YES; 
}