IOS- video player simple package

IOS- video player simple package

Package video player, we first need to understand the implementation of video player, can play MediaPlayer to use video playback system before iOS9, recommend using the AVFoundation framework for video iOS9. Only if you are using
to play video both are very simple, but compared to MediaPlayer, AVPlayer for video playback can be controlled better, through some custom controls to achieve video playback pause and so on. So here’s AVPlayer’s video playback.

Packaged video player, first of all need to implement video player, and then consider how to package, you can make it easier to use in the future.

Video player layout

First, the use of Xib to create CLAVPlayerView UIView inheritance for bearing the player, so that when we use external, CLAVPlayerView can be directly added in the controller View or Cell, as for the player to play or pause operation to CLAVPlayerView management. Here’s a look at the structure of CLAVPlayerView.

The structure of IOS- video player simple package

The CLAVPlayerView layout is very simple, the key is to add and control hierarchy constraints, adding constraints as long as they carefully add one by one there is no problem, need to pay attention to hierarchical control, can be seen from the figure above four order parallel control is added to CLAVPlayerView, should pay attention to their hierarchical relationships, avoid mutual occlusion.

Video player implementation

After the layout is completed, that is, to achieve the player function, we will be divided into four parts of the player function to complete

One, through the play button to achieve video playback.

The first CLAVPlayerView load needs to be added to the imageView player layer layer, the mask and the bottom toolbar are hidden, click on the middle of the play button, start playing video and hide the play button. So we need to do some processing in CLAVPlayerView’s awakeFromNib method when loading CLAVPlayerView.

  1. The initialization of AVPlayer and AVPlayerLayer, and add AVPlayerLayer to the imageView layer, set the playerLayer in layoutSubviews frame// and playerLayer self.player to initialize the player = [[AVPlayer alloc]init]; self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player] playerLayer [self.imageView.layer addSublayer:self.playerLayer] imageView; / / add; – (void) layoutSubviews {[super layoutSubviews]; self.playerLayer.frame = self.imageView.bounds;}
  2. Create AVPlayerItemNSURL *url = [NSURL, URLWithString:@, “” [] = self.playerItem = [AVPlayerItem playerItemWithURL:url] according to the URL of the video playback;
  3. Set the Slider origin and the maximum minimum point set Slider [self.progressSlider setThumbImage:[UIImage imageNamed:@ / / picture “thumbImage” forState:UIControlStateNormal] [self.progressSlider setMaximumTrackImage:[UIImage “MaximumTrackImage”; imageNamed:@ forState:UIControlStateNormal] [self.progressSlider setMinimumTrackImage:[UIImage imageNamed:@ “;” MinimumTrackImage “forState:UIControlStateNormal];
  4. Add a tap gesture to imageView, click on the imageView toolbar is displayed //imageView add *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector UITapGestureRecognizer sign (tapAction:)]; [self.imageView addGestureRecognizer:tap]; note: if you use Xib imageVIew to add gestures, get returns the firstObject need to loadNibNamed when loading the Xib, the Xib is View, if you get lastObject. Is the tap method of gesture, wrong tap gesture object without View.
  5. Other controls display and state settings / hidden cover version of self.coverView.hidden = YES; / / set the toolbar state self.toolView.alpha = 0; self.isShowToolView = NO; / / set the toolbar play button state self.playOrPauseBtn.selected = NO; the cover only appeared after the broadcast on, click on the replay and then hide, so hidden can be directly used to hide, and need to display the toolbar and we, in order to make the toolbar display animation, here by setting toolView alpha to display or hide the toolbar, and through the isShowToolView toolView to record the show or hide.
  6. Click the play button in the middle – (IBAction) playOrPauseBigBtnClick: (UIButton * sender) {/ / hide among the play button, the play button for the selected toolbar sender.hidden = YES; self.playOrPauseBtn.selected = YES; / / [self.player replaceCurrentItemWithPlayerItem:self.playerItem] [self.player to replace the broadcast content; play]; [self addProgressTimer];}

At this point, when we click the middle play button, the player can play the video.

Two. Display and hide toolbar

When playing, when you click imageView, the toolbar will appear at the bottom. You can view the current playing time, the total video time, or pause video, full screen playback and other operations. If there is no action, the toolbar will automatically hide after 5 seconds. When the status is not played, click imageView and intermediate play button effect, start playing video.

  1. After adding the timer for 5 seconds, hide the bottom toolbar and provide a way to remove the timer. / * * toolView display start time, 5S (void) – hidden toolView * / addShowTime [NSTimer scheduledTimerWithTimeInterval:5.0 target:self {self.showTime = selector:@selector (upDateToolView) userInfo:nil repeats:NO]; [[NSRunLoop mainRunLoop]addTimer:self.showTime forMode:NSRunLoopCommonModes];} / * * * toolView (void) upDateToolView hidden – {self.isShowToolView = self.isShowToolView; [UIView animateWithDuration:0.5 animations:^{self.toolView.alpha! = 0;} / * * remove}]; timer * / – (void) removeShowTime {[self.showTime invalidate]; self.showTime = nil;}
  2. Tap imageView click gesture, here is divided into several cases, when not playing video, click on the imageView will not display the toolbar, click the play button and the middle but the same, start playing a video playback process, click on the imageView will display the toolbar, click the toolbar and if the pause button, pause, then the toolbar will not disappear, start playing video, toolbar in 5 seconds away. Tap imageView / * * * / gesture method (void) – tapAction: (UITapGestureRecognizer * tap) {/ / when not playing, click imageView equivalent to click on the middle of the play button, start playing video if (self.player.status = = AVPlayerStatusUnknown) {[self playOrPauseBigBtnClick:self.playOrPauseBigBtn]; return;} / / record bottom toolbar to show or hide the status of self.isShowToolView = self.isShowToolView; / /! If you need to add a toolbar display, animation display if (self.isShowToolView) [UIView animateWithDuration:0.5 animations:^{{self.toolView.alpha = 1; / /}]; when the play button to add the toolbar playing timer, 5 seconds after the toolbar to hide if (self.playOrPauseBtn.selected) {[self addShowTime] If you need to hide the toolbar;} / / remove, timer, and}else{[self removeShowTime] [UIView toolbar hidden; animateWithDuration:0.5 animations:^{self.toolView.alpha = 0;}}}];
  3. Play / pause button in the toolbar click also need to do some processing, when in a suspended state, the alpha value is set to 1, and the timer is removed, start playing video, then re add the timer started after 5 seconds to make the toolbar disappear. Specific code will be detailed in the play time, Slider and video playback synchronization.

Three. Play time, Slider and video playback synchronization

The playback time, video total time, and Slider sliding in the bottom toolbar are synchronized with the video playback time.

  1. Add video playback and Slider timer, every 1 seconds, repeated calls to update time label and Slider slider / * * * / – add slider timer (void) addProgressTimer [NSTimer timerWithTimeInterval:1.0 target:self {self.progressTimer = selector:@selector (updateProgressInfo) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop]addTimer:self.progressTimer forMode:NSRunLoopCommonModes];} / * * * / – remove the slider timer (void) removeProgressTimer invalidate] self.progressTimer {[self.progressTimer = nil; update slider and timeLabel;} / * * * / – (void updateProgressInfo) {NSTimeInterval currentTime = CMTimeGetSeconds (self.player.currentTime); NSTimeInterval durationTime = CMTimeGetSeconds (self.player.currentItem.duration); Self.timeLabel.text = [self timeToStringWithTimeInterval:currentTime]; self.allTimeLabel.text [self = timeToStringWithTimeInterval:durationTime]; self.progressSlider.value = CMTimeGetSeconds (self.player.currentTime) / CMTimeGetSeconds (self.player.currentItem.duration); if (self.progressSlider.value = = 1) {[self removeProgressTimer]; self.coverView.hidden = NO;}} to obtain the current playback time and total time is CMTime, they need to be transformed to NSTimeInterval and the second into a minute and time will translate the proposed methods / * * conversion play method of time and the total time of the * – (NSString) timeToStringWithTimeInterval: (NSTimeInterval) interval; Min {NSInteger = interval / Sec (NSInteger = 60; NSInteger Interval = 60; NSString, *intervalString = [NSString, stringWithFormat:@,%02ld:%02ld, Min, Sec], return, intervalString,}
  2. When you click the play button to start playing the middle when adding a timer, synchronized playback time and Slider, click on the toolbar button when playing on pause pause, need to pause the video, and remove the timer, restart the playback when adding a timer, and start playing on the toolView / * * pause button click event * / – (IBAction) (playOrPauseBtnClick: UIButton * sender) {/ / play button selected YES state selected NO, suspended state. Sender.selected = sender.selected; if (!! sender.selected) {self.toolView.alpha = 1; [self removeShowTime]; [self.player pause]; [self removeProgressTimer];}else{[self addShowTime]; [self.player play]; [self addProgressTimer];}}
  3. Slider drag jump play video
    , according to Slider slide, drag, slide position, play video, need to listen to Slider press, drag (data change), release three stages. When the press is pressed, the timer is removed, and when the drag is dragged, the current playing time is immediately calculated according to the value of the drag and displayed on the label, and the current playing time is calculated when the data is loosened, and the current broadcast time is switched to play. Slider drag and click event / * * * / – (IBAction) touchDownSlider: (UISlider * sender) {/ / remove press down the listener [self removeProgressTimer]; [self removeShowTime];} – (IBAction) valueChangedSlider: (UISlider * sender) {/ / slider drag calculation corresponding points of the playing time of NSTimeInterval currentTime (self.player.currentItem.duration) = CMTimeGetSeconds * sender.value; self.timeLabel.text = [self timeToStringWithTimeInterval:currentTime];} – (IBAction) touchUpInside: (UISlider * sender) {[self addProgressTimer]; / / slider drag calculation corresponding to the current playback time NSTimeInterval currentTime (self.player.currentItem.duration) = CMTimeGetSeconds * sender.value; / / seekToTime: play jump to the current playback time of [self .player seekToTime:CMTimeMakeWithSeconds (currentTime, NSEC_PER_SEC) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero]; [self addShowTime];}

Four. Replay button and full screen play button

  1. In the method of updating the Slider timer in the judgment calls per second when after the video playback, display and replay button cover View, the realization of the Slider value is set to 0 methods and recall the click Slider when released, the current playback time is set to 0, to cover the View hidden, and call the middle of the play button start playing. Click on the replay button * / / * * – (IBAction) repeatBtnClick: (UIButton * sender) {self.progressSlider.value = 0; [self = touchUpInside:self.progressSlider]; self.coverView.hidden YES; [self playOrPauseBigBtnClick:self.playOrPauseBigBtn];}
  2. To achieve full screen playback
    full screen playback controller Moda to full screen playback controller a full screen play, create a full screen playback controller CLFullViewController, which support about the direction of rotation of the Moda CLFullViewController controller, and add CLAVPlayerView to CLFullViewController View and frame can be set up, when to exit full screen, CLFullViewController and dismiss the CLAVPlayerView frame is set to the original value. Can set the rotation and rotation direction of
    – CLFullViewController (UIInterfaceOrientationMask) supportedInterfaceOrientations {return UIInterfaceOrientationMaskLandscape;} – (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation {return YES;} / * * full screen full screen playback button click the button click event * / – (IBAction) fullViewBtnClick: (UIButton * sender) {sender.selected = sender.selected; [self videoplayViewSwitchOrientation:sender.selected];}! Full screen pop-up player – * / / * * (void) videoplayViewSwitchOrientation: (BOOL) isFull (isFull) {if {[self.contrainerViewController presentViewController:self.fullVc animated:NO completion:^{[self.fullVc.view addSubvi Ew:self]; =; [UIView animateWithDuration:0.15 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{self.frame = self.fullVc.view.bounds;}} {completion:nil];}]; else [self.fullVc dismissViewControllerAnimated:NO completion:^{[self.contrainerViewController.view addSubview:self] [UIView animateWithDuration:0.15 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{; self.frame = CGRectMake (0, 200, self.contrainerViewController.view.bounds.size.width, self.contrainerViewController.view.bounds.size.width * 9 / 16);}}}}]; completion:nil]; Note: you need to get the outside controller to Moda the full screen playback controller, so add the contrainerViewController attribute to the CLAVPlayerView to get the controller.

Simple package

This player has achieved the basic functions, then consider how to package can make us more convenient to use, in fact, we have the most complete package, do is to provide a simple and easy to use interface to the next, so that the external call can easily achieve the player.

  1. Provides class methods to quickly create player + (instancetype) videoPlayView {return [[[NSBundle mainBundle]loadNibNamed:@ CLAVPlayerView owner:nil options:nil]lastObject]}
  2. Video resources should be determined by outside, so we provide the urlString attribute is used to receive video resources, and then rewrite the set method to play video resources needed to play a video set / * * * / – (void) setUrlString: (NSString * urlString) {_urlString = urlString; NSURL = [NSURL self.playerItem = *url URLWithString:urlString]; [AVPlayerItem playerItemWithURL:url];}

At this time we use in external player is very simple, without considering the internal logic, only need to quickly create CLAVPlayerView, added to the View controller, the frame set, and then specify the video resources on it.

- (void) viewDidLoad viewDidLoad] [self {[super; setUpVideoPlayView]; self.playView.urlString = @ "";} - (void) setUpVideoPlayView [CLAVPlayerView {self.playView = videoPlayView]; self.playView.frame = CGRectMake (0, 200, self.view.frame.size.width, self.view.frame.size.width * 9 / 16); self.playView.contrainerViewController = self; [self.view addSubview:self.playView];}

Finally, the video player is about the same

IOS- video player simple package
video player

There are many places need to be improved, some functions have not been achieved, for example for two bit Button, the future can be used to download the video switch and control of the barrage, playing after the share button is not realized. Source code has been uploaded to CLxxcc-GitHub, welcome to download and make comments.

If there is anything wrong in the article, please point out. I’m xx_cc, a guy who’s grown up but hasn’t got enough of two.