Swift avfoundation avplayer video player--swift Learn (10)

Source: Internet
Author: User
Tags bind notification center
player

For resource playback, you should use the Avplayer class. You can use the Avplayeritem instance to manage the display state of the entire resource, and use the Avplayeriteamtrack class to manage the display state of individual tasks. You can use the Avplayerlayer class to display the playback resources

A player is a control class that you use to manage a resource player, such as starting a play, ending a play, a specific time, and so on. You can use a Avplayer instance to play a separate resource. You can use a Avqueueplayer (Avplayer subclass) class to play a resource queue. On MacOS, you can choose to play the video using the Avplayerview in the Avkit frame.
..... manipulating different types of resources

The way you configure a resource player may depend on the kind of resource you want to play. In general, there are two types of files: file resources, such as local files, camera resources, media libraries, and so on, stream files, streaming files, network video, and so on to load and play file resources, there are several steps to play a file resource: Create a resource with Avurlasset Create a Avplayitem instance by using a resource to bind with item by Avplayer Wait until the status feature of item indicates that you are ready to play (you can use Key-value listening state changes) to create and prepare a streaming media player.

Initialize a Avplayeritem instance by using a URL (you cannot use the Avasset instance to replace the streaming file directly)

Let URL = Nsurl ("http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8")
Videoitem = Avplayeritem (url : URL)   self.playerItem.addObserver (self,forkeypath: "Status", Options:. NEW,CONTEXT:NIL)//monitor status
videoplayer = Avplayer (PlayerItem:self.playerItem)

When you bind Playeritem and player, it becomes ready to play, and when it becomes ready to play, Playeritem creates a avasset and Avassettrack instance that you can use to check the contents of the streaming media.
You can get the video length by Playitem the Duration property, and when the video becomes ready to play, this property will get the correct duration of the video.
You can listen for status video playback status, such as the above code. play a separate resource

Videoplayer.play ()//Play
Playback Speed
Videoplayer.rate = 2//Speed

A value of 1 indicates a normal playback speed, and setting the speed to 0 is equivalent to pausing. It also supports reverse playback, by setting the speed to a negative value, you set the Canplayreverse property to support the reverse playback state, its default speed is the -1,canplayslowreverse property speed between 0 to 1, The speed of the Canplayfastreverse property is a value less than-1. Reposition the playhead

By using Seektotime: You can move the playback to a specific time:

Let Fivesecondsin = Cmtimemake (30, 1)//current 20th frame, 1 frames per second, current playback time 20/1
        videoplayer.seektotime (fivesecondsin)// Jump to Fivesecondsin

However, Seektotime: methods are more biased towards performance than precision. If you want to jump to a certain progress very precisely, you should use SeekToTime:toleranceBefore:toleranceAfter:

Videoplayer.seektotime (Fivesecondsin, Tolerancebefore:kcmtimezero, Toleranceafter:kcmtimezero)

When playback is complete, the playhead is exactly where it ends, even if you're using play, to get back to where it started after the video has finished playing. We can register a avplayeritemdidplaytoendtimenotification notification at the Notification Center. In the callback method of the notification, you can set the parameter to Kcmtimezero by Seektotime:

Listen for playback end
    Nsnotificationcenter.defaultcenter (). Addobserver (Self, selector: #selector ( Fcfavplayercontroller.playitemdidreachend (_:)), Name:avplayeritemdidplaytoendtimenotification, Object:videoitem)

func playitemdidreachend (notifacation:nsnotification) {
    videoplayer.seektotime (Kcmtimezero)
}
Play multiple Resources

You can use Avqueueplayer to play a resource queue, Avqueueplayer is a subclass of Avplayer, and initializes a avqueueplayer:

Let playItem1 = Avplayeritem (Url:nsurl (string: "Http://tsmusic128.tc.qq.com/37023937.mp3")!)
Let playItem2 = Avplayeritem (Url:nsurl (string: "Http://down.treney.com/mov/test.mp4")!)

Let items = Nsarray (array: [PLAYITEM1,PLAYITEM2]) let
queueplayer = Avqueueplayer (Items:items as! [Avplayeritem])
Let layer = Avplayerlayer (player:queueplayer)
layer.frame = CGRectMake (+, A, cgrectgetwidth (self.view.frame)-
Layer.backgroundcolor = Uicolor.bluecolor (). Cgcolor
self.view.layer.addSublayer (layer)
queueplayer.play ()

You can use play () to play the resource queue, just like Avplayer, the queue plays each resource sequentially, and if you want to play in a resource, you can use Advancetonextitem.
You can also use Insertitem:afteritem:,removeitem:,removeallitem: Modify the resource queue. When you want to add a new resource, you'd better use Caninsertitem:afteritem: first to determine if the queue can insert new resources, the second parameter in nil is to test the new resource appended to the end of the queue.

Let Playnewitem = Avplayeritem (Url:nsurl (string: "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8" )!)

If Queueplayer.caninsertitem (Playnewitem, Afteritem:nil) {
    Queueplayer.insertitem (Playnewitem, Afteritem:nil)
 }
Monitor Playback

You can listen to the rendering status of the resources currently being played and the various aspects of playing the project, which is useful for state changes that cannot be directly controlled, such as:
* If users use multithreading to switch between different apps, the speed of the player may be reduced to 0
* If you are playing a remote media, the Loadedtimerange and Seekabletimerange properties of the item will change as more and more data is available. These properties will tell you which time periods of the resource are available.
* The CurrentItem property of the player will change as new item is created
* The Tracks property of item during playback may change with playback, generally when the content has a variety of transcoding mode, when the encoding mode switch tracks will change
* Player, item status may change if playback fails or some other reason
You can use Key-value to listen for changes to these properties. change of listening state

When the status of the player or item changes, it sends a notification. If a resource fails to play for some reason, the status changes to Avplayerstatusfailed or avplayeritemstatusfailed, and the attribute error will have a description of why it cannot be played.
AV Foundation does not describe what thread the return notification is in, and if you want to update the UI, you must make sure that any relevant UI code is in the main thread, for example:

Monitor state properties, Videoitem.addobserver (self, Forkeypath: "Status", Options:.) New, Context:nil)//monitor Network Load Condition Properties Videoitem.addobserver (self, Forkeypath: "Loadedtimeranges", Options:. New, Context:nil) override Func Observevalueforkeypath (keypath:string, Ofobject object:anyobject?, change: [String : Anyobject], context:unsafemutablepointer<void>) {Let Playitem:avplayeritem = Object as!  Avplayeritem if KeyPath = = "Status" {if Playitem.status = = avplayeritemstatus.failed {Let error = Playitem.error Print (error) return} print ("Playing ..., total video length \ (cmtimegetseconds (pl  ayitem.duration))}else if KeyPath = = "Loadedtimeranges" {Let array = playitem.loadedtimeranges let Timerange = Array.first?. Cmtimerangevalue//This buffer time range let Startsecondes = Cmtimegetseconds ((timerange?.
        Start)!); Let Durationseconds = Cmtimegetseconds ((timerange?.
        Duration)!) Let Totalbuffer = Startsecondes +Durationseconds//Buffer total length print ("Buffer total length \ (totalbuffer)")}}
 
Tracking Display Status

You can get a avplayerlayer readyfordisplay attribute notification tracking time when the resource has a display content.

You can use AddPeriodicTimeObserverForInterval:queue:usingBlock: or AddBoundaryTimeObserverForTimes:queue:usingBlock: To track playback progress. This way you know the time that has been completed and the time remaining, and the synchronization action updates the UI. AddPeriodicTimeObserverForInterval:queue:usingBlock: This method passes in a cmtime structure time, each time period, block will callback once, start and end of time, also will callback once. AddBoundaryTimeObserverForTimes:queue:usingBlock: This is an array of cmtime structures passed in, and when the time is played into the array, the block will be recalled once.
You can also use Removetimeobserver: Cancel the Observer.

For both of these methods, Avfoundation does not guarantee that the block will be recalled every time the point is reached, and if the previous block is not executed, the next one will not be recalled. So you should make sure that the block is not too time consuming.

//tracking time let durations = cmtimegetseconds (asset.duration) Let Firsttrack = Cmtimemakewithseconds (durations/3.0, 1) Let Secondtrack = Cmtimemakewithseconds (durations*2.0/3.0, 1) let times = [Nsvalue (cmtime:firsttrack), Nsvalue
    (Cmtime:secondtrack)] Self.videoplayer.addBoundaryTimeObserverForTimes (Times, Queue:nil) {print ("xxxxx")} 
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: 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.