2013-10-28 3 views
0

내 앱은 현재 기능적으로 동시에 2 개의 동영상을 재생하지만 내가 본 모든 SO 답변은 많은 키 - 값 코드를 사용합니다. 아래에 열거 된 최소한의 것을 수행하는 것이 좋지 않거나 잘못 되었습니까?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]; 

과 KVO의 :

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

     } 
    } 
}