In this post, we will learn how to add video as background in our iOS application. To achieve this, we can use AVPlayer class. Let’s us start, first create a new project with single view application and name it “BackgroundVideo-Demo”.
Steps to add video as background in objective c
Open your ViewController.m file and create a method named addMoviePlayer. Inside this method we will add our AVPlayer code. First drag the video into your project. Secondaly, import AVFoundation.framework
#import AVFoundation/AVFoundation.h
You can download a sample video from given below link
First, we need to get path of our video, we can get it by pathForResource method. After getting video parh, we will create URL by initializing it with the video path.
NSString *videoPath = [[NSBundle mainBundle] pathForResource:@”NycTraffic” ofType:@”mp4″];
Now create an instance of AVPlayerItem and pass our videoURL to it.
Create your videoPlayer using AVPlayer and initialize it with playerItem.
AVPlayer* videoPlayer = [AVPlayer playerWithPlayerItem:playerItem];
Finally, we will create a layer of our player and give it a frame, then we will add it to our view’s layer.
AVPlayer* videoPlayer = [AVPlayer playerWithPlayerItem:playerItem];
Additionally we set our player to mute, so that no sounds will play.
[videoPlayer setMuted:YES];
Lastly, call addMoviePlayer method in viewDidLoad of your viewcontroller.
Run your code, you will see player playing the video. But since there is no repeat node available in AVPlayer. Our video will play only once. Therefore we have to check when our video stops playing and at that particular event we have to restart it. For this we will add notification handler
Registering for AVPlayerItemDidPlayToEndTimeNotification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:)
Complete Code:
Now run your code you will see video loops in the background.