Simple encapsulation of video players in IOS _ios

Source: Internet
Author: User


If the use of only playing video is very simple, but compared to mediaplayer,avplayer for video playback more controllable, you can customize some of the controls to achieve video playback pause, and so on. So here's the video playback using Avplayer.

Video Player layout

First use Xib to create Clavplayerview inheritance UIView to host the player so that when we use it externally, we can add clavplayerview directly to the controller view or cell. As for player playback or suspend operation to Clavplayerview to manage. Let's look at the structure of the Clavplayerview.

The structure of the Clavplayerview

Clavplayerview layout is very simple, focus on the constraints of the addition and control-level relationships, add constraints as long as their own carefully added to the problem, you need to pay attention to the control of the hierarchical relationship, from the above figure can be seen four controls are in order to add in parallel to the Clavplayerview, Pay attention to their level of relationship, avoid mutual occlusion.

Video Player Implementation

After the layout is completed, is to implement the player function, we have the player function roughly divided into four parts to complete

A. Video playback through the play button.

First of all, you need to add the player layer to the ImageView layer Clavplayerview load, and the mask and bottom sidebar must all be hidden, click the Middle Play button, the video starts playing and hides the play button. So we need to do some processing on the Clavplayerview awakefromnib method when loading the Clavplayerview.

1, initialize Avplayer and Avplayerlayer, and add Avplayerlayer to ImageView layer, set layoutsubviews frame in Playerlayer

Initialize the player and playerlayer
self.player = [[Avplayer alloc]init];
Self.playerlayer = [Avplayerlayer playerLayerWithPlayer:self.player];
Add Playerlayer
[Self.imageView.layer AddSublayer:self.playerLayer] on ImageView;
-(void) layoutsubviews
 [super layoutsubviews];
 Self.playerLayer.frame = self.imageView.bounds;

2, according to play the video URL to create Avplayeritem

Nsurl *url = [Nsurl urlwithstring:@ "Http://"];
Self.playeritem = [Avplayeritem Playeritemwithurl:url];

3, set the slider origin and the largest point of the smallest point picture

Set slider
[Self.progressslider setthumbimage:[uiimage imagenamed:@ "Thumbimage"] forstate: UIControlStateNormal];
[Self.progressslider setmaximumtrackimage:[uiimage imagenamed:@ "Maximumtrackimage"] ForState:UIControlStateNormal ];
[Self.progressslider setminimumtrackimage:[uiimage imagenamed:@ "Minimumtrackimage"] ForState:UIControlStateNormal ];

4, add tap Gestures to ImageView, click ImageView to display the toolbar

ImageView Add gesture
uitapgesturerecognizer *tap = [[UITapGestureRecognizer alloc]initwithtarget:self action:@ Selector (tapaction:)];
[Self.imageview Addgesturerecognizer:tap];

Note: If you use Xib to add gestures to imageview, then you need to get the firstobject of the returned array by loadnibnamed loading xib, and if you get xib, Get the tap gesture that will error the tap Gesture object without view method.

5, other control display and the setting of the state

Hide cover version
Self.coverView.hidden = YES;
Sets the toolbar state
Self.toolView.alpha = 0;
Self.isshowtoolview = NO;
Set the toolbar Play button status
self.playOrPauseBtn.selected = NO;

This cover only appears after the playback, click Replay and then hide, so use hidden to hide directly, and the toolbar needs to be repeated, and we in order to make the toolbar display animation effect, here by setting Toolview alpha to show or hide the toolbar, And through Isshowtoolview to record the Toolview display or hide.

6, the Middle play button click

-(Ibaction) Playorpausebigbtnclick: (UIButton *) Sender {
 //Hidden Center play button, toolbar play button is selected
 Sender.hidden = YES;
 self.playOrPauseBtn.selected = YES;
 Replace the playback content
 [Self.player ReplaceCurrentItemWithPlayerItem:self.playerItem];
 [Self.player play];
 [Self addprogresstimer];

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

Two. Display and hide of the tool bar

When you play the state, when you click ImageView, the bottom toolbar pops up, and you can view the current playback time, total video time, or pause the video, Full-screen playback, and so on. If there is no action, the toolbar is automatically hidden after 5 seconds. And when the state is not played, click the ImageView and the middle Play button effect, start playing video.

1, add timer, 5 seconds after hiding the bottom toolbar, and provide a way to remove the timer.

/** Toolview When the display starts to time, after 5s hide Toolview * * *
-(void) addshowtime
{ = [Nstimer scheduledtimerwithtimeinterval:5.0 target:self selector: @selector (Updatetoolview) Userinfo:nil Repeats:no];
 [[Nsrunloop Mainrunloop] formode:nsrunloopcommonmodes];
/** will toolview hidden
/-(void) Updatetoolview
 self.isshowtoolview =!self.isshowtoolview;
 [UIView animatewithduration:0.5 animations:^{
  self.toolView.alpha = 0;}
/** Removal Timer *
/(void) removeshowtime
 [ invalidate]; = nil;

2, ImageView tap gestures to achieve, here is divided into several cases, when the video did not play, click ImageView will not show the toolbar, but the same as clicking the Middle Play button, start playing video, play the process of clicking on the ImageView will show the toolbar, If you click on the Pause button on the toolbar and the playback is paused, the toolbar will not disappear, the video is restarted, and the toolbar disappears in 5 seconds.

/** ImageView Tap Gesture Method * *
-(void) Tapaction: (UITapGestureRecognizer *) tap
 //When not playing state, Click ImageView equivalent to clicking the Middle Play button to start playing video
 if (self.player.status = = Avplayerstatusunknown) {
 The status of the toolbar shown or hidden at the bottom of the record
 Self.isshowtoolview =!self.isshowtoolview;
 If you need a toolbar display, add an animated display
 if (self.isshowtoolview) {
  [UIView animatewithduration:0.5 animations:^{
   Self.toolView.alpha = 1;
  When the play button for the toolbar is played, add the timer, and after 5 seconds the toolbar hides
  if (self.playOrPauseBtn.selected) {
   [self addshowtime];
 If you need to hide the toolbar, remove the timer, and hide the toolbar
  [self removeshowtime];
  [UIView animatewithduration:0.5 animations:^{
   self.toolView.alpha = 0;}

3, the toolbar Play/pause button Click also need to do some processing, when in a paused state, the toolbar alpha value set to 1, and the timer removed, restart playback video, then add the timer to start the timer, 5 seconds after the toolbar disappeared. The specific code will be in the playback time, slider and video playback synchronization in detail.

Three. Playback time, slider and video playback synchronization

The playback time, total video time, and slider slide in the bottom sidebar need to be synchronized with the video playback time.

1. Add video playback and slider timer, repeat call Update time label and slider slider every 1 seconds

 /** Slider Timer Add * *-(void) Addprogresstimer {self.progresstimer = [Nstimer timerwithtimeinterval:1.0 target:self Sel
  Ector: @selector (updateprogressinfo) Userinfo:nil Repeats:yes];
 [[Nsrunloop Mainrunloop]addtimer:self.progresstimer formode:nsrunloopcommonmodes];
  /** Remove Slider Timer/-(void) Removeprogresstimer {[Self.progresstimer invalidate];
 Self.progresstimer = nil; /** Update slider and Timelabel/(void) Updateprogressinfo {nstimeinterval currenttime = cmtimegetseconds (self.player.cur

  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 (

   if (Self.progressSlider.value = = 1) {[Self removeprogresstimer];
  Self.coverView.hidden = NO; } 

The current playback time and total time obtained are cmtime types, they need to be converted to nstimeinterval and converted to minutes and times, the conversion method is presented

/** conversion Playback time and total time of the method * *
-(NSString *) Timetostringwithtimeinterval: (nstimeinterval) interval;
 Nsinteger Min = interval/60;
 Nsinteger Sec = (nsinteger) interval%;
 NSString *intervalstring = [NSString stringwithformat:@ "%02ld:%02ld", min,sec];
 return intervalstring;

2, when you click on the Middle Play button to start playing the time to add a timer, sync update playback time and slider, when playing the toolbar pause button to pause playback, you need to pause the video, and remove the timer, restart playback when adding timers, and start playing

/** Toolview Click event on pause button/
-(Ibaction) Playorpausebtnclick: (UIButton *) Sender {
 //Play Status button selected is Yes, The paused state selected to No.
 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 for slider press, drag (data change), loosen three stages. When pressed, the timer is removed, and the current playback time is calculated immediately based on the dragged value and displayed on the label, the current playback time is calculated when it is released, and jumps to the current playback time for playback.

/** slider Drag and click event/
-(Ibaction) Touchdownslider: (UISlider *) Sender {
 //press down to remove listener
 [self Removeprogresstimer];
 [Self removeshowtime];
-(Ibaction) Valuechangedslider: (UISlider *) Sender {
 //calculate the playback time for slider-dragged points nstimeinterval
 = Cmtimegetseconds (self.player.currentItem.duration) * sender.value;
 Self.timeLabel.text = [self timetostringwithtimeinterval:currenttime];
-(Ibaction) Touchupinside: (UISlider *) Sender {
 [self addprogresstimer];
 Calculates the current slider drag corresponding play time
 nstimeinterval currenttime = cmtimegetseconds (self.player.currentItem.duration) * Sender.value;
 Seektotime: Playback jump to current playback time
 [Self.player seektotime:cmtimemakewithseconds (CurrentTime, nsec_per_sec) Tolerancebefore:kcmtimezero Toleranceafter:kcmtimezero];
 [Self addshowtime];

Four. Replay button and full screen playback button implementation

1, in the timer called the Update slider method to determine when the video playback finished, show the cover view, and the replay button implementation, in fact, is the slider value set to 0 and recall the Click Slider Release method, the current playback time to 0, Re-hide the shaded view and call the middle play button to start playing.

/** Replay Button Click * *
(ibaction) Repeatbtnclick: (UIButton *) Sender {
 self.progressSlider.value = 0;
 [Self touchUpInside:self.progressSlider];
 Self.coverView.hidden = YES;
 [Self playOrPauseBigBtnClick:self.playOrPauseBigBtn];

2, full screen playback of the implementation

Full-screen playback requires the controller Moda a full screen playback controller for Full-screen playback, create Full-screen playback controller Clfullviewcontroller, and make it support the rotation of the left and right direction, Moda out Clfullviewcontroller Controller, and add Clavplayerview to Clfullviewcontroller view and set the frame, and when you exit the full screen, Dismiss off the Clfullviewcontroller and then set the Clavplayerview frame to its original value.
Clfullviewcontroller setting can rotate and rotate direction

-(Uiinterfaceorientationmask) supportedinterfaceorientations
 return Uiinterfaceorientationmasklandscape;
-(BOOL) Shouldautorotatetointerfaceorientation: (uiinterfaceorientation) tointerfaceorientation
 return YES;

Full Screen play button click event

/** Full Screen button click event * * (ibaction) Fullviewbtnclick: (UIButton *) Sender {sender.selected =!sender.selected;
[Self videoplayViewSwitchOrientation:sender.selected]; /** Eject full Screen player */-(void) Videoplayviewswitchorientation: (BOOL) Isfull {if (isfull) {[Self.contrainerviewcontroller Pre
   SentViewController:self.fullVc animated:no completion:^{[Self.fullVc.view addsubview:self]; =; [UIView animatewithduration:0.15 delay:0.0 options:uiviewanimationoptionlayoutsubviews animations:^{= sel
  } Completion:nil];
 }]; else {[SELF.FULLVC dismissviewcontrolleranimated:no completion:^{[Self.contrainerViewController.view addsubview:s

   ELF]; [UIView animatewithduration:0.15 delay:0.0 options:uiviewanimationoptionlayoutsubviews animations:^{self.frame = CGR Ectmake (0, Self.contrainerViewController.view.bounds.size.width,
   Self.contrainerViewController.view.bounds.size.width * 9/16); } completion:nIL];
 }]; }

Note: Here you need to get the outside controller to Moda out the full screen playback controller, so add the Contrainerviewcontroller attribute to the Clavplayerview to get the controller.

Simple encapsulation

At this point has implemented the player basic functions, and then consider how to encapsulate can make us more convenient to use, in fact, we have to do most of the encapsulation, the next thing to do is to provide a simple and easy-to-use interface, so that external can easily invoke the implementation of the player.

1. Provide class method to quickly create a player

+ (instancetype) Videoplayview
{return [[[
 nsbundle mainbundle]loadnibnamed:@ ' Clavplayerview ' Owner:nil Options:nil]lastobject];

2. The resources to play video should be determined externally, so we provide the resources that the URLString property uses to receive video, and then play the video by overriding its set method
/** Video Resource set method that needs to be played * *

-(void) seturlstring: (NSString *) urlstring
 _urlstring = urlstring;
 Nsurl *url = [Nsurl urlwithstring:urlstring];
 Self.playeritem = [Avplayeritem playeritemwithurl:url];

The external use of the player is very simple at this time, without considering the internal logic, simply create the Clavplayerview, add it to the Controller view, set its frame, and then assign it to play the video resource.

-(void) viewdidload {
 [super viewdidload];
 [Self setupvideoplayview]; 
 self.playView.urlString = @ "Http://";
-(void) Setupvideoplayview
 Self.playview = [Clavplayerview Videoplayview];
 Self.playView.frame = CGRectMake (0, 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 roughly like this


There are many areas that need to be perfected, and some functions are not implemented, such as two placeholder buttons, which can be used to download video and control the screen, and the sharing button is not implemented after the playback. After the realization to everyone to continue to share, the above is the entire content of this article, I hope this article content for everyone can help, if there is doubt you can message exchange.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.