Basic use of Avplayer

Source: Internet
Author: User

In iOS development, there are usually two ways to play video, one is to use MPMoviePlayerController (you need to import mediaplayer.framework), and one is to use Avplayer. The difference between these two classes can be referred to http://stackoverflow.com/questions/8146942/avplayer-and-mpmovieplayercontroller-differences, In short, MPMoviePlayerController is easier to use, less powerful than Avplayer, and Avplayer is a bit more cumbersome to use, but more powerful. This blog mainly introduces the basic use of the next avplayer, because bloggers are also just contact, so there are problems we directly pointed out ~

In the development, simply using the Avplayer class is unable to display the video, to add the video layer to Avplayerlayer, so that the video can be displayed, so first add the following properties in Viewcontroller @interface

@property (nonatomic, Strong) Avplayer **playeritem; @property (nonatomic ,weak  Iboutletplayerview  *playerview;

Where Playerview inherits from UIView, but overrides the set and get methods to add the player to Playerview Avplayerlayer so that the video can be displayed smoothly

Declare a Avplayer object in PlayerView.h, because the default layer is Calayer, and Avplayer can only be added to Avplayerlayer, so we change the layerclass so that the default layer of Playerview is changed. We can assign the Avplayer object initialized in Viewcontroller to the Player property of Avplayerlayer.

PlayerView.h

@property (nonatomic, strong) Avplayer *player;

playerview.m

+returnclass-(Avplayer *return [(Avplayerlayer *-( void) Setplayer: (Avplayer *) player {    *) [self layer] setplayer:player];}

Then perform the initialization in Viewdidload:

Nsurl *videourl = [Nsurl urlwithstring:@"Http://www.jxvdy.com/file/upload/201405/05/18-24-58-42-627.mp4"];self.playeritem=[Avplayeritem Playeritemwithurl:videourl]; [Self.playeritem addobserver:self Forkeypath:@"Status"Options:nskeyvalueobservingoptionnew Context:nil];//Monitoring Status Property[Self.playeritem addobserver:self Forkeypath:@"loadedtimeranges"Options:nskeyvalueobservingoptionnew Context:nil];//Listening Loadedtimeranges PropertiesSelf.player = [Avplayer PlayerWithPlayerItem:self.playerItem];[[NsnotificationcenterDefaultcenter]Addobserver: Selfselector:@selector(movieplaydidend:)name:AvplayeritemdidplaytoendtimenotificationObject: Self.Playeritem];

The online video link is first stored in Videourl, and then initialized Playeritem,playeritem is the object that manages the resource (A player item manages the presentation state of a asset with WHI CH it is associated. A Player Item contains player item tracks-instances of Avplayeritemtrack-that correspond to the tracks in the asset.)

Then listen for the status and Loadedtimerange properties of the Playeritem, which have three statuses:

Avplayerstatusunknown,

Avplayerstatusreadytoplay,

Avplayerstatusfailed

When status equals Avplayerstatusreadytoplay the video is ready to play, we can call the play method to play.

The Loadedtimerange property represents the progress that has been buffered, and listening to this property can update the buffering progress in the UI and is a useful property.

Finally, add a notification to listen to whether the video has finished playing, and then implement the Kvo method:

- (void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (nsdictionary *) Change context: (void*) Context {Avplayeritem*playeritem = (Avplayeritem *)Object; if([KeyPath isequaltostring:@"Status"]) { if([playeritem status] = =Avplayerstatusreadytoplay) {NSLog (@"Avplayerstatusreadytoplay"); Self.stateButton.enabled=YES; Cmtime Duration= Self.playerItem.duration;//Get total video lengthCGFloat totalsecond = Playeritem.duration.value/playeritem.duration.timescale;//convert into seconds_totaltime = [self converttime:totalsecond];//convert to play time[Self customvideoslider:duration];//Customizing the UISlider appearanceNSLog (@"Movie Total Duration:%f", Cmtimegetseconds (duration)); [Self monitoringPlayback:self.playerItem];//Monitor playback status}Else if([playeritem status] = =avplayerstatusfailed) {NSLog (@"avplayerstatusfailed"); }    } Else if([KeyPath isequaltostring:@"loadedtimeranges"]) {nstimeinterval timeinterval= [self availableduration];//Calculate buffering ProgressNSLog (@"Time interval:%f", timeinterval); Cmtime Duration=self.playerItem.duration; CGFloat totalduration=cmtimegetseconds (duration); [Self.videoprogress setprogress:timeinterval/totalduration Animated:yes]; }} -(Nstimeinterval) availableduration {Nsarray*loadedtimeranges =[[Self.playerView.player CurrentItem] loadedtimeranges]; Cmtimerange Timerange= [Loadedtimeranges.firstobject Cmtimerangevalue];//Get buffer Area floatStartseconds =cmtimegetseconds (timerange.start);floatDurationseconds =cmtimegetseconds (timerange.duration); Nstimeinterval result= Startseconds + durationseconds;//Calculate Total Buffer Progress returnresult;} -(NSString *) ConvertTime: (cgfloat) second{nsdate*d =[NSDate Datewithtimeintervalsince1970:second]; NSDateFormatter*formatter =[[NSDateFormatter alloc] init];if(second/3600>=1) {[Formatter Setdateformat:@"HH:mm:ss"]; } Else{[Formatter Setdateformat:@"Mm:ss"]; } nsstring*showtimenew =[Formatter stringfromdate:d];returnshowtimenew;}

This method mainly responds to the status and Loadedtimeranges properties, when the status state becomes Avplayerstatusreadytoplay, the video is ready to play, and we can get some video information, including the length of the video, With the play button device enabled, click on the play method to play the video. There is also a Monitoringplayback method at the bottom of the Avplayerstatusreadytoplay:

- (void) Monitoringplayback: (Avplayeritem *) Playeritem {self.playbacktimeobserver= [Self.playerView.player Addperiodictimeobserverforinterval:cmtimemake (1,1) Queue:null usingblock:^(Cmtime time) {cgfloat Currentsecond= Playeritem.currenttime.value/playeritem.currenttime.timescale;//calculation is currently in the first few seconds [self updatevideoslider:currentsecond]; NSString*timestring =[self converttime:currentsecond]; Self.timeLabel.text= [NSString stringWithFormat:@"%@/%@", Timestring,_totaltime]; }];}

Monitoringplayback is used to listen for status per second,-(ID) Addperiodictimeobserverforinterval: (cmtime) interval queue: (dispatch_queue_t) Queue usingblock: (void (^) (cmtime time)) block; This method is the key, the interval parameter is the response interval, which is set to the response per second, the queue is the queues, and null represents the execution of the main thread. You can update a UI, such as the current time of the progress bar, and so on.

As a player, in addition to playing, pausing and other functions. There is also an essential function, that is to show the current playback progress, as well as the buffer area, my idea is that, with Uiprogressview to display the buffered playable area, with UISlider to show the current playing progress, of course, here to UISlider do some customization, The code is as follows:

-(void   =     cmtimegetseconds (duration); Uigraphicsbeginimagecontextwithoptions ((cgsize) { 1 , 1 }, NO, 0.0f  ); UIImage  *transparentimage = 

So UISlider only the middle of the thumbimage, and thumbimage around the color has become transparent, is only used to display the current playback time. Uiprogressview is used to display the currently buffered area without any custom modifications, as the storyboard looks like:

Add the UISlider to the Uiprogressview, and the effect becomes like this:

This basic buffering function is done, of course, there are some features did not do, such as volume, sliding screen fast forward and so on, we have time to do their own play down ~ The final effect is as follows:

Finally attach the demo link: Https://github.com/mzds/AVPlayerDemo


Basic use of Avplayer

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: info-contact@alibabacloud.com 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.