iOS背景视频循环GIF UIWebview或VideoPlayer

时间:2016-09-17 10:31:25

标签: ios video uiwebview avplayer

我需要编写一个应用程序,其中View的背景中有不同的短视频循环。这些环通常应具有10-30秒的长度。我想知道在性能和内存经济性方面哪些更好(从appstore下载时应该将应用程序捆绑在一起)

a)使用UIWebview作为背景,其中循环播放视频的动画.gif文件 b)使用一些VideoPlayerView(AVPlayer)作为背景,使用类似m4v的文件 c)我还没有考虑过的另一种选择

还会有音频,但音频没有链接到视频

1 个答案:

答案 0 :(得分:0)

- (void)playIntroVideo
{
//  NSBundle *bundle = [NSBundle mainBundle];
//  //  NSString *moviePath = iPadDevice ? [bundle pathForResource:@"IntroVideo" ofType:@"mp4"] : [bundle pathForResource:@"IntroVideo_iPhone" ofType:@"mp4"];
//  NSString *moviePath = [bundle pathForResource:@"IntroVideo" ofType:@"mp4"];
//  NSURL *movieURL = [NSURL fileURLWithPath:moviePath];

CGRect frame = self.movieView.frame;
frame.origin.x=-200;
frame.size.width+=200;

AVAsset *avAsset = [AVAsset assetWithURL:movieURL];

AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:avAsset];
gen.appliesPreferredTrackTransform = YES;
CMTime time = CMTimeMakeWithSeconds(0.0, 600);
NSError *error = nil;
CMTime actualTime;

CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
UIImage *selectedImage = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);

UIImageView *img = [[UIImageView alloc] initWithImage:selectedImage];
img.frame = frame;
[self.movieView addSubview:img];

AVPlayerItem *avPlayerItem =[[AVPlayerItem alloc]initWithAsset:avAsset];
self.avplayer = [[AVPlayer alloc]initWithPlayerItem:avPlayerItem];
avPlayerLayer =[AVPlayerLayer playerLayerWithPlayer:self.avplayer];
[avPlayerLayer setVideoGravity:AVLayerVideoGravityResize];

if (iPhoneDevice)
    [avPlayerLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

[avPlayerLayer setFrame:frame];

[self.movieView.layer addSublayer:avPlayerLayer];

[self.avplayer seekToTime:kCMTimeZero];

//  Not affecting background music playing
NSError *sessionError = nil;

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&sessionError];

//  [self.avplayer setVolume:0.0f];
[self.avplayer setActionAtItemEnd:AVPlayerActionAtItemEndNone];

}
- (void)viewDidLoad
{
[super viewDidLoad];
[self playIntroVideo];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.avplayer play];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];

[self.avplayer pause];
//  self.avplayer = nil;

[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:[self.avplayer currentItem]];

}

- (void)playerItemDidReachEnd:(NSNotification *)notification
{
AVPlayerItem *p = [notification object];
[p seekToTime:kCMTimeZero];
}