我正在开发一个相继播放多个视频的视频应用程序.视频存储在AVPlayerItem的数组中. AVQueuePlayer使用这些AVPlayerItem进行初始化,它会自动播放该阵列中的视频.
问题是当它改变播放下一个视频时,它被卡住了几分之一秒,或者在它从一个转换到另一个时创建了一个混蛋.我想通过某种动画来改善这种转换,比如淡入淡出,而视频被改变.
我的AVQueuePlayer代码:
AVQueuePlayer *mediaPlayer = [[AVQueuePlayer alloc] initWithItems:arrPlayerItems]; playerLayer=[AVPlayerLayer playerLayerWithPlayer:mediaPlayer]; playerLayer.frame=self.bounds; playerLayer.videoGravity = AVLayerVideoGravityResizeAspect; playerLayer.needsDisplayOnBoundsChange = NO; [self.layer addSublayer:playerLayer]; self.layer.needsDisplayOnBoundsChange = YES; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemPlayEnded:) name:AVPlayerItemDidPlayToEndTimeNotification object:[mediaPlayer currentItem]];
我尝试在转换时创建一个新的层,并通过减少其不透明度并增加新层的不透明度(创建所需的淡入淡出效果)来对旧层进行动画处理,但是它不能按需要工作.
-(void)TransitionInVideos { if (roundf(CMTimeGetSeconds(mediaPlayer.currentTime))==roundf(CMTimeGetSeconds(mediaPlayer.currentItem.duration))) { [self.layer addSublayer:playerLayerTmp]; //Animation for the transition between videos [self performSelector:@selector(FadeIn) withObject:nil afterDelay:0.3]; [self performSelector:@selector(FadeOut) withObject:nil afterDelay:0.3]; } } -(void)FadeIn { CABasicAnimation* fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"]; fadeAnim.fromValue = [NSNumber numberWithFloat:1.0]; fadeAnim.toValue = [NSNumber numberWithFloat:0.0]; fadeAnim.duration = 2.0; [playerLayer addAnimation:fadeAnim forKey:@"opacity"]; [self performSelector:@selector(HideLayer) withObject:nil afterDelay:2.0]; } -(void)FadeOut { CABasicAnimation* fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"]; fadeAnim.fromValue = [NSNumber numberWithFloat:0.0]; fadeAnim.toValue = [NSNumber numberWithFloat:1.0]; fadeAnim.duration = 1.0; [playerLayerTmp addAnimation:fadeAnim forKey:@"opacity"]; [self performSelector:@selector(ShowLayer) withObject:nil afterDelay:1.0]; } -(void)HideLayer { playerLayer.opacity=0.0; } -(void)ShowLayer { playerLayerTmp.opacity=1.0; }
如何将转换应用于AVQueuePlayer中的视频?
解决方法
我们可以设置AVMutableVideoCompositionLayerInstruction的不透明度,将导出视频或将AVPlayer作为VideoComposition属性添加到视频中,并创建淡入淡出效果.
[layerInstruction setOpacityRampFromStartOpacity:1.0 toEndOpacity:0.0 timeRange:CMTimeRangeMake(CMTimeSubtract([mutableComposition duration],CMTimeMake(Transition_Time,1)),[mutableComposition duration])]; [layerInstruction setOpacityRampFromStartOpacity:0.0 toEndOpacity:1.0 timeRange:CMTimeRangeMake(kCMTimeZero,CMTimeMake(1,1))];
更完整的例子:https://www.raywenderlich.com/30200/avfoundation-tutorial-adding-overlays-and-animations-to-videos