Charles Yao
Charles Yao

Reputation: 53

How to sync multiple AVPlayer while play the same local video

I have to play the same local video file with the AVPlayer at the same time, and I created 4 AVPlayer instance, and the AVPlayerLayers was added to tha same layer. But the question is that 4 player were not begin at the same time. How to make them begin at the same time? here is my code:

self.players = @[].mutableCopy;
    CMAudioClockCreate(kCFAllocatorDefault, &_syncClock);
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:self.url];
    for (NSInteger i = 0; i<playerNum; i++) {
        AVPlayer *avPlayer = [AVPlayer playerWithPlayerItem:item.copy];
        AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
        //设置模式
        playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        playerLayer.contentsScale = [UIScreen mainScreen].scale;
        CGPoint pos = [playerOriginArr[i] CGPointValue];
        playerLayer.frame = CGRectMake(pos.x, pos.y, playerSize.width, playerSize.height);
        [self.playBackBgView.layer addSublayer:playerLayer];
        avPlayer.masterClock = _syncClock;
        [avPlayer.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        [avPlayer play];
        [self.players addObject:avPlayer];
    }

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                    change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"status"] && [object isKindOfClass:[AVPlayerItem class]]) {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if (playerItem.status == AVPlayerStatusReadyToPlay) {
        for (AVPlayer *player in self.players) {
            if (player.currentItem == playerItem) {
                [player prerollAtRate:1.0 completionHandler:^(BOOL finished) {
                    if (finished) {
                    }
                }];
                player.automaticallyWaitsToMinimizeStalling = NO;//如果是
                NSLog(@"setRate");
                [player setRate:1.0 time:kCMTimeInvalid atHostTime:CMClockGetTime(_syncClock)];
            }
        }
    }
}

}

Upvotes: 2

Views: 1378

Answers (1)

Gordon Childs
Gordon Childs

Reputation: 36072

Create just one AVPlayer and create multiple AVPlayerLayers from that.

The layers will be synchronized.

Upvotes: 1

Related Questions