2013-10-28 199 views
0

我的應用程序目前在功能上同時播放2個視頻,但我所見到的所有答案都是利用了許多Key-Value代碼。如果我只是做了下面列出的最低限度,那麼它是壞/錯?在AVPlayer中播放視頻

viewDidLoad中

AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL URLWithString:firstVideo.videoURL]]; 
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset]; 
    self.player1 = [AVPlayer playerWithPlayerItem:item]; 
    [topPlayer setMovieToPlayer:self.player1]; 


    AVURLAsset *asset2 = [AVURLAsset assetWithURL:[NSURL URLWithString:secondVideo.videoURL]]; 
    AVPlayerItem *item2 = [AVPlayerItem playerItemWithAsset:asset2]; 
    self.player2 = [AVPlayer playerWithPlayerItem:item2]; 
    [bottomPlayer setMovieToPlayer:self.player2]; 

    ((AVPlayerLayer *)[self.topPlayer layer]).videoGravity = AVLayerVideoGravityResizeAspectFill; 
    ((AVPlayerLayer *)[self.bottomPlayer layer]).videoGravity = AVLayerVideoGravityResizeAspectFill; 
    [self.player1 play]; 
    [self.player2 play]; 

上面的代碼是我用來播放視頻,並能正常工作。偶爾會有1秒鐘的延遲,我怎麼才能等到兩個視頻都準備好播放,然後播放它們呢?

回答

2

使用KVO觀察玩家的狀態,並在兩人的狀態準備就緒時播放視頻。

[yourPlayerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:nil]; 

和志願:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{ 
    if ([keyPath isEqualToString:@"status"]) { 
     AVPlayerStatus status = [change[NSKeyValueChangeNewKey] integerValue]; 
     switch (status) { 
      case AVPlayerStatusUnknown: 
       //do something 
       break; 
      case AVPlayerStatusReadyToPlay: 
      { 
       //check which avplayer is ready, by check the parametric object isEqual:yourPlayerItem 
       //use a bool value to record the ready status. after two bools are YES, then play the video 
      } 
       break; 
      case AVPlayerStatusFailed: 
      { 
       AVPlayerItem *playerItem = (AVPlayerItem *)object; 
       [self assetFailedToPrepareForPlayback:playerItem.error]; 
      } 
       break; 

     } 
    } 
}