How to play video with AVPlayerViewController (AVK

2019-04-02 04:30发布

问题:

How to play a video using AVPlayerLayer, and AVPlayerViewControler in xamarin iOS?

playerItem = new AVPlayerItem(new NSUrl("https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
        player = new AVPlayer(playerItem);
        AVcontroller.Player = player;
        AVcontroller.View.Layer.Frame = this.View.Bounds;
        this.View.AddSubview(AVcontroller.View);
        //AVcontroller.SetFullscreen(true, true);
        AVcontroller.Player.Play();

回答1:

There are two ways to play a video, choose one of them, like the code:

 public override void ViewDidLoad ()
    {
        //Set the movie file path
        string moviePath = NSBundle.MainBundle.PathForResource ("loadingAnimation", "mov");
        NSUrl movieUrl = NSUrl.FromFilename (moviePath);

        //Using MPMoviePlayerController(using MediaPlayer)
        MPMoviePlayerController mpC = new MPMoviePlayerController (movieUrl);
        mpC.ControlStyle = MPMovieControlStyle.None;
        mpC.View.Frame = new CGRect (50, 50, 200, 200);
        mpC.View.BackgroundColor = UIColor.Clear;
        mpC.ShouldAutoplay = true;
        this.Add (mpC.View);
        mpC.Play ();

        //Using AVPlayer(using AVFoundation)
        AVPlayer avPlayer;
        AVPlayerLayer playerLayer;
        AVAsset asset;
        AVPlayerItem playerItem;
        asset = AVAsset.FromUrl (movieUrl);
        playerItem = new AVPlayerItem (asset);
        avPlayer = new AVPlayer (playerItem);
        playerLayer = AVPlayerLayer.FromPlayer (avPlayer);
        playerLayer.Frame = new CGRect (50, 300, 200, 200);
        View.Layer.AddSublayer (playerLayer);
        avPlayer.Play ();
    }

Hope it can help you.



回答2:

AVPlayer avp;
AVPlayerViewController avpvc;


var url = NSUrl.FromString(yourURL);
            avp = new AVPlayer(url);
            avpvc = new AVPlayerViewController();
            avpvc.Player = avp;
            AddChildViewController(avpvc);
            View.AddSubview(avpvc.View);
            avpvc.View.Frame = View.Frame;
            avpvc.ShowsPlaybackControls = true;
            avp.Play();

This is all done in viewDidLoad and its working fine now.