IOS-Video Loop playback

Source: Internet
Author: User

After recording the video, we want to play our little video in an infinite loop on the preview layer of the recorded video, which is cool, and we have three choices:
1.MPMoviePlayerController
2.AVPlayer
3.avassetreader+avassetreadertrackoutput

But our preview layer is custom, so mpmovieplayercontroller can only be filtered out immediately, so with, then we will use Avplayer , although the avplayer up to 16 can be created, performance is not used The avassetreader+avassetreadertrackoutput method is good, but it is enough for this kind of video to play. (PS: Next blogger will write an article on how to use Avassetreader+avassetreadertrackoutput to achieve video playback)

Avplayer
AVPlayer本身并不能显示视频,而且它也不像MPMoviePlayerController有一个view属性。如果AVPlayer要显示必须创建一个播放器层AVPlayerLayer用于展示,播放器层继承于CALayer, 有了AVPlayerLayer之添加到控制器视图的layer中即可。要使用AVPlayer首先了解一下几个常用的类:AVAsset:主要用于获取多媒体信息,是一个抽象类,不能直接使用。AVURLAsset:AVAsset的子类,可以根据一个URL路径创建一个包含媒体信息的AVURLAsset对象。AVPlayerItem:一个媒体资源管理对象,管理者视频的一些基本信息和状态,一个AVPlayerItem对应着一个视频资源。

Let's get acquainted with these classes of Avplayer.
So the steps to use Avplayer to play video are as follows:
1. Create Avplayeritem to instantiate the Avplayer and monitor the status of the video

-(Avplayer *) player{if(!_player) {Avplayeritem*playeritem =[self getplayitem]; _player=[[Avplayer Alloc]initwithplayeritem:playeritem]; //you can use Avplayeritem to monitor the status of this video}return_player;}-(Avplayeritem *) getplayitem{NSString*cachepath=[Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastobject]; NSString*savepath=[CachePath Stringbyappendingpathcomponent:moviepath]; Nsurl*saveurl=[Nsurl Fileurlwithpath:savepath]; //instantiate Avplayeritem by file URLAvplayeritem *playeritem =[[Avplayeritem alloc] initwithurl:saveurl]; returnPlayeritem;}

2. Create a preview layer (Avplayerlayer) with Avplayer and add it to the visible layer to play

Avplayerlayer *playerlayer = [Avplayerlayer playerLayerWithPlayer:self.player];      = _viewcontrain.bounds;     Playerlayer.videogravity=avlayervideogravityresizeaspectfill; // Video Fill Mode      [_viewcontrain.layer Addsublayer:playerlayer];     [Self.player play];

3. Monitor the video's properties via KVO to see if the playback is complete, how small the playback length is, how much is buffered, etc.

/** * Add progress update to player*/-(void) addprogressobserver{Avplayeritem*playeritem=Self.player.currentItem; Uiprogressview*progress=self.progress;//This is set to execute once per second[Self.player Addperiodictimeobserverforinterval:cmtimemake (1.0,1.0) Queue:dispatch_get_main_queue () usingblock:^(Cmtime time) {floatCurrent=cmtimegetseconds (time); floatTotal=cmtimegetseconds ([playeritem duration]); NSLog (@"%.2FS is currently playing.", current); if(current) {[Progress setprogress: ( current/Total ) Animated:yes]; }   }];}#pragmaMark-kvo/** * Add monitoring to Avplayeritem * * @param playeritem Avplayeritem Object*/-(void) Addobservertoplayeritem: (Avplayeritem *) playeritem{//Monitor State Properties, note that Avplayer also has a status property, and can also get playback status by monitoring its status[Playeritem addobserver:self Forkeypath:@"Status"options:nskeyvalueobservingoptionnew Context:nil];//monitoring Network Load condition Properties[Playeritem addobserver:self Forkeypath:@"loadedtimeranges"options:nskeyvalueobservingoptionnew Context:nil];}-(void) Removeobserverfromplayeritem: (Avplayeritem *) Playeritem{[playeritem removeobserver:self Forkeypath:@"Status"]; [Playeritem removeobserver:self Forkeypath:@"loadedtimeranges"];}/** * monitor player status via KVO * * @param keypath Monitoring Properties * @param object Monitor * @param change Status changed * @param context Context*/- (void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (Nsdictionary<nsstring *,ID> *) Change context: (void*) context{Avplayeritem*playeritem=Object; if([KeyPath isequaltostring:@"Status"]) {avplayerstatus status= [[Change Objectforkey:@"New"] intvalue]; if(status==Avplayerstatusreadytoplay) {NSLog (@"playing ..., total video length:%.2f", Cmtimegetseconds (playeritem.duration)); }    }    Else if([KeyPath isequaltostring:@"loadedtimeranges"]) {Nsarray*array=playeritem.loadedtimeranges; Cmtimerange Timerange= [Array.firstobject Cmtimerangevalue];//the buffer time range        floatStartseconds =cmtimegetseconds (Timerange.start); floatDurationseconds =cmtimegetseconds (timerange.duration); Nstimeinterval Totalbuffer= Startseconds + durationseconds;//Total buffer lengthNSLog (@"Total buffers:%.2f", Totalbuffer); }}

In this way, we have created the method of Avplayer video playback.

So we call the video playback method when the video recording is complete.

- (void) Captureoutput: (Avcapturefileoutput *) captureoutput Didfinishrecordingtooutputfileaturl: (NSURL *) OutputFileURL Fromconnections: (Nsarray *) connections Error: (NSERROR *) error{NSLog (@"----recording ends----");}- (void) completehandle{//keep playing when you are done[_capturevideopreviewlayer Removefromsuperlayer]; //Play Video//1. Create a playback layer//why this call delay 1 seconds, we said with Avcapturemoviefileoutput to record the video, is the side record writing, even if the recording is complete, the real video is still written, about the time is about 1.2 seconds delay. Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (1.0* nsec_per_sec)), Dispatch_get_main_queue (), ^{            //in this method call, create the second part of the Avplayer playback video            2play [self addnotification] by creating a preview layer (Avplayerlayer) from Avplayer and adding to the visible layer;  }); }

Add monitoring after video playback to loop video playback
 /** * Add player Notifications*/-(void) addnotification{//add playback completion notification to Avplayeritem[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (playbackfinished:) Name: AvplayeritemdidplaytoendtimenotificationObject: Self.player.currentItem];}-(void) removenotification{[[Nsnotificationcenter Defaultcenter] removeobserver:self];}/** * PLAY COMPLETE notification * * @param notification notification Object*/-(void) playbackfinished: (Nsnotification *) notification{NSLog (@"video playback is complete."); //repeat playback after playback is complete//jump to the latest point in time to start playing[_player Seektotime:cmtimemake (0,1)]; [_player play];}

IOS-Video Loop playback

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.