In iOS application development some time we may have situation where we want to show our own controls on AVPlayer. Suppose user want to show the playback slider on the bottom of the screen and two buttons on the left and right side of the screen to control the speed of the video .
To implement this we can create a view with required buttons and slider and assign action to designated view controller. The steps are as follows:
1) Create a view controller and then design the xib as per the need and create necessary outlets and action of the objects .
2) Then in implementation file create an instance of AVPlayerItem .
3) Initialize AVPLayer with the AVPlayerItem instance
4) Create an AVPLayerLayer instance
To implement this we can create a view with required buttons and slider and assign action to designated view controller. The steps are as follows:
1) Create a view controller and then design the xib as per the need and create necessary outlets and action of the objects .
2) Then in implementation file create an instance of AVPlayerItem .
NSURL *url =[NSURL URLWithString:@"http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];
//create player item
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
3) Initialize AVPLayer with the AVPlayerItem instance
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
5) Now insert the playerLayer to the view's layer hierarchy
[self.view.layer insertSublayer:playerLayer atIndex:0];
That's all our design is done.
Now our job is to run the slider, speed the video when user tap on button and play and pause the video .To implement these all feature we can register observer .
6) To check the status of the playing item we can register for key path observing like this :
[playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
Then implement the method
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
}
This method is core method of KVO(Key-value-observing) and is called every time when any changes occur in the property of the registered object .In this method we can check for different key path and take action accordingly like this :
if ([keyPath isEqualToString:@"status"]) {
}
7)To track the buffering of the video register for key path playbackLikelyToKeepUp
[playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
8) We can register an observer to listen for when the video is ended :
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playerDidEndVideo) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
No comments:
Post a Comment