在iOS 5中按顺序播放两个视频,没有任何间隙或暂停

时间:2012-03-15 19:08:12

标签: objective-c ios avfoundation mpmovieplayer avqueueplayer

在我的应用中,我应该立即播放第一个视频,然后播放第二个视频,这将重复播放。所以,起初我使用了MPMoviePlayerController,但两个视频之间已经有黑屏。所以,我在某处阅读,在我的情况下,我应该使用AVFoundation。那是我使用AVQueuePLayer和两个AVPLayerItem,我用我的NSURL创建的。但问题是,在第一个视频完成后,有一个很长的停顿。在第二次视频开始之前几乎持续0.5秒。怎么删除它?有什么方法可以使用?所以,我真的很感激任何帮助!我非常需要它,尽快。谢谢!

这是我使用的所有方法:

- (void) configureAVPlayer {
   self.queuePlayer.actionAtItemEnd = AVPlayerActionAtItemEndPause; 

   [[NSNotificationCenter defaultCenter]
       addObserver:self
       selector:@selector(playerItemDidReachEnd:)
       name:AVPlayerItemDidPlayToEndTimeNotification
       object:self.queuePlayer];

   self.isFirstVideoFinished = NO;

   [self playVideos];

}

- (void) playVideos {
   [self setPlayerItemsForQueue];
   [self.videoHolder setPlayer:self.queuePlayer];

}

- (void) setPlayerItemsForQueue {
NSURL *fileURL = [[NSBundle mainBundle]
                  URLForResource:[self getStringForMode:self.currentMode] withExtension:@"mp4"];

NSMutableString *secondFile = [self getStringForMode:self.currentMode];
[secondFile appendString:@"Second"];
NSURL *secondFileUrl = [[NSBundle mainBundle] URLForResource:secondFile withExtension:@"mp4"];

AVAsset *firstAsset = [AVAsset assetWithURL:fileURL];

AVPlayerItem *firstVideoItem = [AVPlayerItem playerItemWithAsset:firstAsset];//[AVPlayerItem playerItemWithURL:fileURL];

AVAsset *secondAsset = [AVAsset assetWithURL:secondFileUrl];
AVPlayerItem *secondVideoItem = [AVPlayerItem playerItemWithAsset:secondAsset];//[AVPlayerItem playerItemWithURL:secondFileUrl];

self.queuePlayer = [AVQueuePlayer queuePlayerWithItems: [NSArray arrayWithObjects:firstVideoItem, secondVideoItem,nil]];

for (AVPlayerItem *playerItem in self.queuePlayer.items) {
    [playerItem addObserver: self forKeyPath: @"status" options:0 context:NULL];
}

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object 
                    change:(NSDictionary *)change context:(void *)context {

dispatch_async(dispatch_get_main_queue(), ^{
    if ([(AVPlayerItem *)object status] == AVPlayerItemStatusReadyToPlay) {
        [self.queuePlayer play];
    }
});

}

- (void) playerItemDidReachEnd:(NSNotification*) notification {

NSMutableString *secondFile = [self getStringForMode:self.currentMode];
[secondFile appendString:@"Second"];
NSURL *secondFileUrl = [[NSBundle mainBundle] URLForResource:secondFile withExtension:@"mp4"];
AVPlayerItem *playerItem = [[ AVPlayerItem alloc ] initWithURL:secondFileUrl];

if ([self.queuePlayer canInsertItem:playerItem afterItem:[notification object]]) {
    [self.queuePlayer insertItem: playerItem afterItem: nil ];
}

}

1 个答案:

答案 0 :(得分:0)

是的,多个AVPlayer对象是您的最佳选择。

我通过主计时器功能解决了这个问题,该功能监视firstVideoItem的当前播放时间,当它从结束时间为0.01秒时,我会在alpha通道上翻转播放器,因此secondVideoItem可见,然后播放secondVideoItem。

在发出播放命令之前,我还使用了[secondVideoItem seekToTime:CMTimeMakeWithSeconds(1,1)],以确保第二个视频已初始化并准备播放。这有很大帮助。