Introduction – Play Video On AVPlayer
Contents
Media playing now days is most common and important functionality that every iOS App developer should know. Playing any media asset can be done by many methods like AVPlayer or WKWebView or etc. While in this tutorial we are going to learn how to play video through AVPlayer class and how to set video on centre mode.
Overview For Video Playing On AVPlayer in Centre Mode
AVPlayer is intended for playing a single media asset at a time. The player instance can be reused to play additional media assets using its replaceCurrentItem(with:) method, but it manages the playback of only a single media asset at a time. The framework also provides a subclass of AVPlayer, called AVQueuePlayer, that you can use to create and manage of queue of media assets to be played sequentially. For More details Go to Page https://developer.apple.com/documentation/avfoundation/avplayer.
Solution & Code For Video Playing On AVPlayer in Centre Mode
First of all use
#import <AVKit/AVKit.h>
in your view controllers .h file and then include delegates
UIViewController
Then in .m File, declare these player variable globally,
@interface SplashViewController (){
AVPlayerViewController *moviePlayerController;
AVPlayer *moviePlayer;
AVPlayerLayer *playerLayer;
}
@end
after declaring use this function in your code for playing video.call this function where ever you want to call and play video.
- (void)playVideo{
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:@"VideoName" ofType:@"mp4"];
NSURL *videoURL = [NSURL fileURLWithPath:moviePath];
moviePlayer = [AVPlayer playerWithURL:videoURL];
playerLayer = [AVPlayerLayer playerLayerWithPlayer:moviePlayer];
playerLayer.frame = self.view.bounds;
[self.view.layer addSublayer:playerLayer];
//Now set videoGravity to aspectFill for showing video on center mode or you can change as their are more video gravity options are available as per your requirement.
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
// Subscribe to the AVPlayerItem's DidPlayToEndTime notification.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:moviePlayer.currentItem];
[moviePlayer play];
}