gpt4 book ai didi

ios - 在 AVPlayer 中播放视频

转载 作者:行者123 更新时间:2023-11-28 22:23:36 25 4
gpt4 key购买 nike

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

查看加载

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

上面的代码是我用来播放视频的所有代码,效果很好。偶尔会有 ~1s 的延迟,我怎么能等到两个视频都准备好播放,然后同时播放它们呢?

最佳答案

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

}
}
}

关于ios - 在 AVPlayer 中播放视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19625580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com