id | title | brief | samplecode | sdk | |||||
---|---|---|---|---|---|---|---|---|---|
A88F34E5-EF29-0F57-9505-1D9AF21E8BE6 |
Play a Video Using AVPlayer |
This recipe shows how to play a video using an AVPlayer and AVPlayerLayer. |
|
-
Add
using AVFoundation;
to the top of the class file. -
Add the following class variable in a
UIViewController
subclass.AVPlayer player; AVPlayerLayer playerLayer; AVAsset asset; AVPlayerItem playerItem;
-
Add a movie file named sample.m4v to the project. There is a sample file included in the project download for this recipe.
-
Ensure that the file's Build Action is set to Content. You can do this by right-clicking on the file and selecting Build Action from the context menu that appears.
-
In the ViewDidLoad method, create an
AVAsset
and pass it to anAVPlayerItem
.asset = AVAsset.FromUrl (NSUrl.FromFilename ("sample.m4v")); playerItem = new AVPlayerItem (asset);
-
Create an AVPlayer and pass it the AVPlayerItem created above.
player = new AVPlayer (playerItem);
-
Create an
AVPlayerLayer
from theAVPlayer
instance and add as a sublayer to the view’s layer.playerLayer = AVPlayerLayer.FromPlayer (player); playerLayer.Frame = View.Frame; View.Layer.AddSublayer (playerLayer);
-
Call the
Play
method of theAVPlayer
instance to play the video.player.Play ();
The AVPlayer
is part of the AVFoundation
framework and is available in the AVFoundation
namespace.