我正在使用 Sprite Kit 和 SKVideoNode 播放短视频。当视频节点添加到场景中时,无论是在初始设置之前还是之后,播放器都会短暂闪烁黑色。
我尝试过使用 AVPlayer 来播放视频而不是直接播放视频,我还使用 KVO 仅在视频显示可以播放时才加载 SKVideoNode。
无论哪种方式,我都会在视频开始播放之前出现黑色闪光。
此外,似乎没有办法将 AVPlayerLayer 添加到 SKScene/SKView,尽管我不知道这是否有帮助。
任何关于下一步尝试的建议都会很棒。
这是我正在使用的代码
- (void)didMoveToView:(SKView *)view
{
if (!self.contentCreated) {
[self createSceneContents];
}
}
- (void)createSceneContents
{
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"IntroMovie" ofType:@"mov"];
NSURL *introVideoURL = [NSURL fileURLWithPath:resourcePath];
self.playerItem = [AVPlayerItem playerItemWithURL:introVideoURL];
self.player = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
[self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
SKSpriteNode *playButton = [SKSpriteNode spriteNodeWithImageNamed:@"PlayButton"];
[playButton setPosition:CGPointMake(CGRectGetMidX(self.view.frame), (CGRectGetMidY(self.view.frame) / 5) * 3)];
[self addChild:playButton];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"status"]) {
if ([[change objectForKey:NSKeyValueChangeNewKey] integerValue] == AVPlayerItemStatusReadyToPlay) {
NSLog(@"Change has the following %@", change);
[self.player prerollAtRate:0 completionHandler:^(BOOL done){
SKVideoNode *introVideo = [SKVideoNode videoNodeWithAVPlayer:self.player];
[introVideo setSize:CGSizeMake(self.size.width, self.size.height)];
[introVideo setPosition:self.view.center];
[self addChild:introVideo];
[introVideo play];
[self.playerItem removeObserver:self forKeyPath:@"status"];
}];
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
这是一段替代代码,它只播放视频并在加载视频和播放视频之间提供相同的黑色闪光。
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"IntroMovie" ofType:@"m4v"];
NSURL *introVideoURL = [NSURL fileURLWithPath:resourcePath];
self.playerItem = [AVPlayerItem playerItemWithURL:introVideoURL];
self.player = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
SKVideoNode *introVideo = [SKVideoNode videoNodeWithAVPlayer:self.player];
[introVideo setSize:CGSizeMake(self.size.width, self.size.height)];
[introVideo setPosition:self.view.center];
[self addChild:introVideo];
[introVideo play];