繁体   English   中英

在AVPlayer中播放视频

[英]Playing videos in AVPlayer

我的应用程序目前在功能上同时播放2个视频,但我所看到的所有SO答案都使用了大量的键值代码。 如果我只做下面列出的最低限度,这是不是错了?

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秒的延迟,我怎么能等到两个视频都准备好播放,然后再播放它们?

使用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;

        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM