简体   繁体   中英

Playing videos in AVPlayer

My app currently plays 2 videos at the same time, functionally, but I all the SO answers i've seen utilizes lots of Key-Value code. Is it bad/wrong if I just do the bare minimum listed below?

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

The above code is all I use to play a video, and it works fine. Occasionally there is a ~1s delay, how can I wait until both the videos are ready to play, then play them both?

use KVO to observer the player's status, and play videos when both's status is ready.

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

and in 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;

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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