有時候會看到某些App,開啟App就會播放高畫質的影片,起初我以為是顯示GIF影像,然而實際上應是無限循環播放影片。比如我在每天都可以思考的公司做過華視新聞App,我合作同事就是實作這一部份。
想要做到其實很簡單,照抄以下程式碼⋯⋯
關鍵就是去觀察影片是否播放到結尾,若是的話就從起點再次播放。
此段程式碼有處理離開App與進入App的狀況,將影片擴大到全螢幕,隱藏播放控制介面。
#import <AVKit/AVKit.h>
@property (nonatomic, strong) AVPlayerViewController *playerViewController;
@property (nonatomic, strong) AVPlayer *videoPlayer;
@property (nonatomic, strong) AVPlayerItem *playerItem;
- (void)viewDidLoad {
[super viewDidLoad];
__weak typeof(self) weakSelf = self; // prevent memory cycle
NSNotificationCenter *noteCenter = [NSNotificationCenter defaultCenter];
[noteCenter addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
[weakSelf.videoPlayer seekToTime:kCMTimeZero];
[weakSelf.videoPlayer play];
}];
[noteCenter addObserverForName:UIApplicationDidBecomeActiveNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
[weakSelf playVideo];
}];
[noteCenter addObserverForName:UIApplicationWillResignActiveNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
[weakSelf pauseVideo];
}];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self playVideo];
}
-(void)viewDidDisappear:(BOOL)animated
{
[self pauseVideo];
NSNotificationCenter *noteCenter = [NSNotificationCenter defaultCenter];
[noteCenter removeObserver:self];
[super viewDidDisappear:animated];
}
-(void)playVideo
{
NSString *videoPath = [[NSBundle mainBundle] pathForResource:@"launch video" ofType:@"mp4"];
NSURL *videoURL =[NSURL fileURLWithPath:videoPath];
if (!self.playerItem) {
self.playerItem = [AVPlayerItem playerItemWithURL:videoURL];
}
if (!self.videoPlayer) {
self.videoPlayer = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
}
if (!self.playerViewController) {
self.playerViewController = [[AVPlayerViewController alloc] init];
self.playerViewController.player = self.videoPlayer;
self.playerViewController.player.volume = 0;
self.playerViewController.view.frame = self.view.bounds;
self.playerViewController.videoGravity = AVLayerVideoGravityResizeAspectFill;
self.playerViewController.showsPlaybackControls = NO;
[backgroundImageView addSubview:self.playerViewController.view];
[backgroundImageView sendSubviewToBack:self.playerViewController.view];
}
[self.videoPlayer play];
}
-(void)pauseVideo
{
[self.videoPlayer pause];
}
感覺很簡單吧~
參考:。

隨意留個言吧:)~