public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            //largely taken from the xamarin website videoplayer tutorial

            //build the path to the location where the movie was saved
            var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
            var library = System.IO.Path.Combine (documents, "..", "Library");
            var urlpath = System.IO.Path.Combine (library, "sweetMovieFilm.mov");

            NSUrl url = new NSUrl (urlpath, false);

            _asset = AVAsset.FromUrl(url);
            _playerItem = new AVPlayerItem (_asset);
            _player = new AVPlayer (_playerItem);

            _playerLayer = AVPlayerLayer.FromPlayer (_player);
            _playerLayer.Frame = View.Frame;
            View.Layer.AddSublayer (_playerLayer);

            //this code makes UI controls sit on top of the movie layer.  Allows you to just place the controls in interface builder
            UIView cameraView = new UIView ();
            this.View.AddSubview (cameraView);
            this.View.SendSubviewToBack (cameraView);
            cameraView.Layer.AddSublayer (_playerLayer);

            _player.Play ();

            this.btnDonePlaying.TouchUpInside += stopPlaying;
        }
 public NSMyVideoView(CoreGraphics.CGRect rect, NSView view, AVPlayerLayer layer)
     : base(rect)
 {
     AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable;
     _view = view;
     _layer = layer;
 }
Exemple #3
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();


            //largely taken from the xamarin website videoplayer tutorial



            //build the path to the location where the movie was saved
            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var library   = System.IO.Path.Combine(documents, "..", "Library");
            var urlpath   = System.IO.Path.Combine(library, "sweetMovieFilm.mov");

            NSUrl url = new NSUrl(urlpath, false);

            _asset      = AVAsset.FromUrl(url);
            _playerItem = new AVPlayerItem(_asset);
            _player     = new AVPlayer(_playerItem);

            _playerLayer       = AVPlayerLayer.FromPlayer(_player);
            _playerLayer.Frame = View.Frame;
            View.Layer.AddSublayer(_playerLayer);

            //this code makes UI controls sit on top of the movie layer.  Allows you to just place the controls in interface builder
            UIView cameraView = new UIView();

            this.View.AddSubview(cameraView);
            this.View.SendSubviewToBack(cameraView);
            cameraView.Layer.AddSublayer(_playerLayer);

            _player.Play();

            this.btnDonePlaying.TouchUpInside += stopPlaying;
        }
Exemple #4
0
        public void PhotoLibraryDidChange(PHChange changeInstance)
        {
            // Call might come on any background queue. Re-dispatch to the main queue to handle it.
            DispatchQueue.MainQueue.DispatchAsync(() => {
                // Check if there are changes to the asset we're displaying.
                PHObjectChangeDetails changeDetails = changeInstance.GetObjectChangeDetails(Asset);
                if (changeDetails == null)
                {
                    return;
                }

                // Get the updated asset.
                // TODO: check return type. Catch! ObjectAfterChanges should be PHObject instead of NSObject https://bugzilla.xamarin.com/show_bug.cgi?id=35540
                Asset = (PHAsset)changeDetails.ObjectAfterChanges;
                if (Asset != null)
                {
                    FavoriteButton.Title = Asset.Favorite ? "♥︎" : "♡";
                }

                // If the asset's content changed, update the image and stop any video playback.
                if (changeDetails.AssetContentChanged)
                {
                    UpdateImage();

                    playerLayer?.RemoveFromSuperLayer();
                    playerLayer = null;
                }
            });
        }
Exemple #5
0
 public NSMyVideoView(CoreGraphics.CGRect rect, NSView view, AVPlayerLayer layer)
     : base(rect)
 {
     AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable;
     _view            = view;
     _layer           = layer;
 }
Exemple #6
0
 public override void ViewDidLoad()
 {
     base.ViewDidLoad();
     VideoLocal.Layer.CornerRadius    = 10;
     VideoInternet.Layer.CornerRadius = 10;
     VideoLocal.TouchUpInside        += delegate {
         AVPlayer      Reproductor;
         AVPlayerLayer CapaRedproductor;
         AVAsset       Recurso;
         AVPlayerItem  RecursoReproducir;
         Recurso                = AVAsset.FromUrl(NSUrl.FromFilename("toystory.mp4"));
         RecursoReproducir      = new AVPlayerItem(Recurso);
         Reproductor            = new AVPlayer(RecursoReproducir);
         CapaRedproductor       = AVPlayerLayer.FromPlayer(Reproductor);
         CapaRedproductor.Frame = new CGRect(50, 100, 300, 300);
         View.Layer.AddSublayer(CapaRedproductor);
         Reproductor.Play();
     };
     VideoInternet.TouchUpInside += delegate {
         AVPlayer      Reproductor;
         AVPlayerLayer CapaRedproductor;
         AVAsset       Recurso;
         AVPlayerItem  RecursoReproducir;
         Recurso                = AVAsset.FromUrl(NSUrl.FromString("https://www.rmp-streaming.com/media/bbb-360p.mp4"));
         RecursoReproducir      = new AVPlayerItem(Recurso);
         Reproductor            = new AVPlayer(RecursoReproducir);
         CapaRedproductor       = AVPlayerLayer.FromPlayer(Reproductor);
         CapaRedproductor.Frame = new CGRect(50, 100, 300, 300);
         View.Layer.AddSublayer(CapaRedproductor);
         Reproductor.Play();
     };
 }
Exemple #7
0
 protected override void OnElementChanged(ElementChangedEventArgs <VideoPlayer> e)
 {
     base.OnElementChanged(e);
     if (Control == null)
     {
         _timer          = new Timer(TimeSpan.FromSeconds(1).TotalMilliseconds);
         _timer.Elapsed += _timer_Elapsed;
     }
     if (e.OldElement != null)
     {
         _timer?.Stop();
         _timer?.Dispose();
         _timer = null;
         _asset?.Dispose();
         _asset = null;
         _playerItem?.Dispose();
         _playerItem = null;
         _player?.Dispose();
         _player = null;
         _playerLayer?.Dispose();
         _playerLayer = null;
     }
     if (e.NewElement != null)
     {
     }
 }
        // Load movies and display movie layers
        private AVPlayerLayer ConfigurePlayer(string movieName, string hostingNodeName)
        {
            var player = AVPlayer.FromUrl(NSUrl.FromFilename(movieName));

            player.ActionAtItemEnd = AVPlayerActionAtItemEnd.None;             // loop

            NSNotificationCenter.DefaultCenter.AddObserver(this, new Selector("PlayerItemDidReachEnd"), AVPlayerItem.DidPlayToEndTimeNotification, player.CurrentItem);

            player.Play();

            // Set an arbitrary frame. This frame will be the size of our movie texture so if it is too small it will appear scaled up and blurry, and if it is too big it will be slow
            var playerLayer = new AVPlayerLayer();

            playerLayer.Player          = player;
            playerLayer.ContentsGravity = AVPlayerLayer.GravityResizeAspectFill;
            playerLayer.Frame           = new CGRect(0, 0, 600, 800);

            // Use a parent layer with a background color set to black
            // That way if the movie is stil loading and the frame is transparent, we won't see holes in the model
            var backgroundLayer = CALayer.Create();

            backgroundLayer.BackgroundColor = NSColor.Black.CGColor;
            backgroundLayer.Frame           = new CGRect(0, 0, 600, 800);
            backgroundLayer.AddSublayer(playerLayer);

            var frameNode = GroundNode.FindChildNode(hostingNodeName, true);
            var material  = frameNode.Geometry.Materials [1];

            material.Diffuse.Contents = backgroundLayer;

            return(playerLayer);
        }
        private void InitializePlayer()
        {
            _player     = new AVPlayer();
            _videoLayer = AVPlayerLayer.FromPlayer(_player);
            var avSession = AVAudioSession.SharedInstance();

            // By setting the Audio Session category to AVAudioSessionCategorPlayback, audio will continue to play when the silent switch is enabled, or when the screen is locked.
            avSession.SetCategory(AVAudioSessionCategory.Playback);

            NSError activationError = null;

            avSession.SetActive(true, out activationError);
            if (activationError != null)
            {
                Console.WriteLine("Could not activate audio session {0}", activationError.LocalizedDescription);
            }

            Player.AddPeriodicTimeObserver(new CMTime(1, 4), DispatchQueue.MainQueue, delegate
            {
                var totalDuration = TimeSpan.FromSeconds(_player.CurrentItem.Duration.Seconds);
                var totalProgress = Position.TotalMilliseconds /
                                    totalDuration.TotalMilliseconds;
                PlayingChanged?.Invoke(this, new PlayingChangedEventArgs(totalProgress, Position, Duration));
            });
        }
		// Load movies and display movie layers
		private AVPlayerLayer ConfigurePlayer (string movieName, string hostingNodeName)
		{
			var player = AVPlayer.FromUrl (NSUrl.FromFilename (movieName));
			player.ActionAtItemEnd = AVPlayerActionAtItemEnd.None; // loop

			NSNotificationCenter.DefaultCenter.AddObserver (this, new Selector ("PlayerItemDidReachEnd"), AVPlayerItem.DidPlayToEndTimeNotification, player.CurrentItem);

			player.Play ();

			// Set an arbitrary frame. This frame will be the size of our movie texture so if it is too small it will appear scaled up and blurry, and if it is too big it will be slow
			var playerLayer = new AVPlayerLayer ();
			playerLayer.Player = player;
			playerLayer.ContentsGravity = AVPlayerLayer.GravityResizeAspectFill;
			playerLayer.Frame = new CGRect (0, 0, 600, 800);

			// Use a parent layer with a background color set to black
			// That way if the movie is stil loading and the frame is transparent, we won't see holes in the model
			var backgroundLayer = CALayer.Create ();
			backgroundLayer.BackgroundColor = NSColor.Black.CGColor; 
			backgroundLayer.Frame = new CGRect (0, 0, 600, 800);
			backgroundLayer.AddSublayer (playerLayer);

			var frameNode = GroundNode.FindChildNode (hostingNodeName, true);
			var material = frameNode.Geometry.Materials [1];
			material.Diffuse.Contents = backgroundLayer;

			return playerLayer;
		}
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            bool IsFirstLogin = NSUserDefaults.StandardUserDefaults.BoolForKey("SmallVidIntro");


            if (IsFirstLogin)
            {
                avasset = AVAsset.FromUrl(NSUrl.FromFilename("an1.mp4"));
            }
            else
            {
                avasset = AVAsset.FromUrl(NSUrl.FromFilename("an2.mp4"));
                NSUserDefaults.StandardUserDefaults.SetBool(true, "SmallVidIntro");
            }

            avplayerItem        = new AVPlayerItem(avasset);
            avplayer            = new AVPlayer(avplayerItem);
            avplayerLayer       = AVPlayerLayer.FromPlayer(avplayer);
            avplayerLayer.Frame = View.Frame;
            View.Layer.AddSublayer(avplayerLayer);
            avplayer.Play();

            NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, MainScreenHandler);
        }
        private void LoadVideoDescView()
        {
            NSArray views = NSBundle.MainBundle.LoadNib("VoteVideoDescView", this, new NSDictionary());

            if (1 == views.Count)
            {
                UIView tempView = Runtime.GetNSObject(views.ValueAt(0)) as UIView;

                if (tempView is VoteImageDescView)
                {
                    var descView = tempView as VoteImageDescView;
                    descView.UpdateUIWith(SelectedVote);

                    descView.Frame = new System.Drawing.RectangleF(0, 0, (float)View.Bounds.Width, (float)View.Bounds.Height);
                    View.AddSubview(descView);

                    _asset      = AVAsset.FromUrl(NSUrl.FromString(SelectedVote.VideoUrl));
                    _playerItem = new AVPlayerItem(_asset);

                    _player            = new AVPlayer(_playerItem);
                    _playerLayer       = AVPlayerLayer.FromPlayer(_player);
                    _playerLayer.Frame = View.Frame;

                    descView.Layer.AddSublayer(_playerLayer);

                    _player.Play();
                }
            }
        }
Exemple #13
0
        public AVMediaPlayer()
        {
            player = new AVPlayer
            {
                ActionAtItemEnd = AVPlayerActionAtItemEnd.Pause,
#if __IOS__
                AllowsAirPlayVideo = true,
#endif
                AllowsExternalPlayback = true,
                Volume = Settings.CurrentVolume,
            };
            resourceDelegate = new MyResourceLoaderDelegate(this);
            timeObserver     = player.AddPeriodicTimeObserver(new CoreMedia.CMTime(5, 30), null, (time) => OnPlabackTimeChanged(player, time));
            rateObserver     = player.AddObserver("rate", NSKeyValueObservingOptions.New, (change) => OnStateChanged(player));

            PlayerLayer     = AVPlayerLayer.FromPlayer(player);
            endTimeObserver = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, (notification) =>
            {
                var avplayerItem = notification?.Object as AVPlayerItem;
                if (avplayerItem == player.CurrentItem)
                {
                    OnFinished(avplayerItem);
                }
            });
            playerDidStallObserver = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.PlaybackStalledNotification, (notification) =>
            {
                var avplayerItem = notification?.Object as AVPlayerItem;
                if (avplayerItem == player.CurrentItem)
                {
                    Console.WriteLine("Handle STalling");
                    isStalled = true;
                    State     = PlaybackState.Buffering;
                }
            });
        }
        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();
            
			LoadNotifications ();
			IsSeeking = false;
			_asset = AVAsset.FromUrl (NSUrl.FromFilename ("sample.m4v"));
			_playerItem = new AVPlayerItem (_asset);

			_player = new AVPlayer (_playerItem); 
			_playerItem.AddObserver (this, (NSString)"status", NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Initial, StatusObservationContext.Handle);
			_playerItem.AddObserver (this, (NSString)"playbackBufferFull", NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Initial, PlaybackBufferFullContext.Handle);
			_playerItem.AddObserver (this, (NSString)"playbackBufferEmpty", NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Initial, PlaybackBufferEmptyContext.Handle);
			_playerItem.AddObserver (this, (NSString)"playbackLikelyToKeepUp", NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Initial, PlaybackLikelyToKeepUpContext.Handle);

			_player.Muted = true;
            _playerLayer = AVPlayerLayer.FromPlayer (_player);
            _playerLayer.Frame = View.Frame;
            
            View.Layer.AddSublayer (_playerLayer);

			AddTapGesture ();
			InitScrubberTimer ();
			SyncScrubber ();
            
            _player.Play ();
			PlayButton.SetTitle ("Pause", UIControlState.Normal);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            _asset      = AVAsset.FromUrl(NSUrl.FromFilename("SampleVideo.mp4"));
            _playerItem = new AVPlayerItem(_asset);

            _playerItem.SeekingWaitsForVideoCompositionRendering = true;
            _playerItem.AddObserver(this, (NSString)"status", NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, StatusObservationContext.Handle);
            NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, (notification) =>
            {
                Console.WriteLine("Seek Zero = true");
                seekToZeroBeforePlaying = true;
                this.updatePlayPauseButton();
            }, _playerItem);

            _player            = new AVPlayer(_playerItem);
            _playerLayer       = AVPlayerLayer.FromPlayer(_player);
            _playerLayer.Frame = this.playerView.Frame;
            this.playerView.Layer.AddSublayer(_playerLayer);

            updateScrubber();
            updateTimeLabel();

            slider.EditingDidBegin        += slider_EditingDidBegin;
            slider.EditingDidEnd          += slider_EditingDidEnd;
            slider.ValueChanged           += slider_ValueChanged;
            playpauseButton.TouchUpInside += playpauseButton_TouchUpInside;

            playing = true;
            _player.Play();
        }
		protected override void OnElementChanged (ElementChangedEventArgs<View> e)
		{
			base.OnElementChanged (e);

			//Get the video
			//bubble up to the AVPlayerLayer
			var url = new NSUrl ("http://www.androidbegin.com/tutorial/AndroidCommercial.3gp");
			_asset = AVAsset.FromUrl (url);

			_playerItem = new AVPlayerItem (_asset);

			_player = new AVPlayer (_playerItem);

			_playerLayer = AVPlayerLayer.FromPlayer (_player);

			//Create the play button
			playButton = new UIButton ();
			playButton.SetTitle ("Play Video", UIControlState.Normal);
			playButton.BackgroundColor = UIColor.Gray;

			//Set the trigger on the play button to play the video
			playButton.TouchUpInside += (object sender, EventArgs arg) => {
				_player.Play();
			};
		}
Exemple #17
0
        protected override void OnElementChanged(ElementChangedEventArgs <VideoView> e)
        {
            if (e.NewElement != null)
            {
                if (string.IsNullOrEmpty(Element.Source))
                {
                    throw new ArgumentException("Source is required.");
                }

                if (base.Control == null)
                {
                    var view = new UIView();
                    SetNativeControl(view);

                    if (Element.ShowControl)
                    {
                        if (Element.IsFromUrl)
                        {
                            if (movieController == null)
                            {
                                var url = NSUrl.FromString(Element.Source);
                                movieController = new MPMoviePlayerController();
                                movieController.ShouldAutoplay = true;
                                movieController.Fullscreen     = true;
                                movieController.ControlStyle   = MPMovieControlStyle.Embedded;
                                movieController.PrepareToPlay();
                                movieController.SourceType = MPMovieSourceType.Streaming;
                                movieController.ContentUrl = url;
                                view.Add(movieController.View);

                                movieController.Play();
                                movieController.SetFullscreen(true, true);
                            }
                        }
                    }
                    else
                    {
                        if (playerItem == null)
                        {
                            asset      = AVAsset.FromUrl(NSUrl.FromFilename(Element.Source));
                            playerItem = new AVPlayerItem(asset);
                            //					AVPlayerItem.DidPlayToEndTimeNotification;

                            player = new AVPlayer(playerItem);
                            player.ActionAtItemEnd = AVPlayerActionAtItemEnd.None;
                            playerLayer            = AVPlayerLayer.FromPlayer(player);


                            view.Layer.AddSublayer(playerLayer);


                            SetRepeat();
                            SetPlaying();
                        }
                    }
                }
            }

            base.OnElementChanged(e);
        }
Exemple #18
0
        protected override void OnElementChanged(ElementChangedEventArgs <View> e)
        {
            base.OnElementChanged(e);

            //Get the video
            //bubble up to the AVPlayerLayer
            //var url = new NSUrl ("http://www.androidbegin.com/tutorial/AndroidCommercial.3gp");
            var url = new NSUrl("file://" + NSBundle.MainBundle.PathForResource("SampleVideo", "mp4"));

            _asset = AVAsset.FromUrl(url);

            _playerItem = new AVPlayerItem(_asset);

            _player = new AVPlayer(_playerItem);

            _playerLayer = AVPlayerLayer.FromPlayer(_player);

            //Create the play button
            playButton = new UIButton();
            playButton.SetTitle("Play Video", UIControlState.Normal);
            playButton.BackgroundColor = UIColor.Gray;

            //Set the trigger on the play button to play the video
            playButton.TouchUpInside += (object sender, EventArgs arg) => {
                _player.Play();
            };
        }
Exemple #19
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            if (string.IsNullOrEmpty(FilePath) || !File.Exists(FilePath))
            {
                NavigationController.PopViewController(true);
            }

            string taskType = Task.TaskType.IdName;

            if (taskType == "LISTEN_AUDIO" || taskType == "REC_AUDIO" || taskType == "TAKE_VIDEO")
            {
                // Load video, play and loop
                playerItem   = AVPlayerItem.FromUrl(NSUrl.FromFilename(FilePath));
                player       = AVQueuePlayer.FromItems(new AVPlayerItem[] { playerItem });
                playerLayer  = AVPlayerLayer.FromPlayer(player);
                playerLooper = AVPlayerLooper.FromPlayer(player, playerItem);

                if (taskType == "TAKE_VIDEO")
                {
                    playerLayer.Frame = View.Frame;
                    View.Layer.AddSublayer(playerLayer);
                }
                else
                {
                    ImageView.Hidden = true;
                    AudioIcon.Hidden = false;
                    DescLabel.Text   = Task.Description;
                }

                player.Play();
            }
            else
            {
                // Load image
                ImageService.Instance.LoadFile(FilePath).Error((e) =>
                {
                    Console.WriteLine("ERROR LOADING IMAGE: " + e.Message);
                    NavigationController.PopViewController(true);
                }).Into(ImageView);
            }

            if (DeleteResult != null)
            {
                UIBarButtonItem customButton = new UIBarButtonItem(
                    UIImage.FromFile("ic_delete"),
                    UIBarButtonItemStyle.Plain,
                    (s, e) =>
                {
                    ConfirmDelete();
                }
                    );

                NavigationItem.RightBarButtonItem = customButton;
            }
        }
Exemple #20
0
 void ResetPlayer1()
 {
     StopPlayer(player1);
     player1Song = null;
     player1?.CurrentItem?.Asset?.CancelLoading();
     ResetPlayer(player1);
     player1      = CreatePlayer();
     player1Layer = AVPlayerLayer.FromPlayer(player1);
 }
Exemple #21
0
 void ResetPlayer2()
 {
     StopPlayer(player2);
     player2Song = null;
     player2?.CurrentItem?.Asset?.CancelLoading();
     ResetPlayer(player2);
     player2      = CreatePlayer();
     player2Layer = AVPlayerLayer.FromPlayer(player2);
 }
Exemple #22
0
        public void AVPlayerLayer_VideoGravity()
        {
            AVPlayerLayer layer = new AVPlayerLayer();

#if XAMCORE_2_0
            Assert.IsNotNull(layer.VideoGravity);
#else
            Assert.IsNotNull(layer.LayerVideoGravity);
#endif
        }
 private void BtnPlay_TouchUpInside(object sender, EventArgs e)
 {
     avAsset             = AVAsset.FromUrl(NSUrl.FromFilename("video.mp4"));
     avPlayerItem        = new AVPlayerItem(avAsset);
     avPlayer            = new AVPlayer(avPlayerItem);
     avPlayerLayer       = AVPlayerLayer.FromPlayer(avPlayer);
     avPlayerLayer.Frame = View.Frame;
     View.Layer.AddSublayer(avPlayerLayer);
     avPlayer.Play();
 }
        protected override void OnElementChanged(ElementChangedEventArgs <View> e)
        {
            base.OnElementChanged(e);
            if (e.NewElement is VideoPlayer parentPlayer)
            {
                _player      = new AVPlayer();
                _playerLayer = AVPlayerLayer.FromPlayer(_player);

                _contentType = parentPlayer.ContentType;
                var url = _contentType == Constants.ContentType.Remote ? new NSUrl(parentPlayer.Source) : new NSUrl(parentPlayer.Source, false);
                _asset      = AVAsset.FromUrl(url);
                _playerItem = new AVPlayerItem(_asset);
                _player.ReplaceCurrentItemWithPlayerItem(_playerItem);

                videoLengthThread = new Thread(new ThreadStart(() =>
                {
                    _totalLength = _player.CurrentItem.Asset.Duration.Seconds;
                    InvokeOnMainThread(() =>
                    {
                        parentPlayer.SoundLength?.Invoke(this, _totalLength);
                    });
                }));
                videoLengthThread.Start();

                parentPlayer.Play += (sender, innere) =>
                {
                    if (videoLengthThread.IsAlive)
                    {
                        videoLengthThread.Abort();
                        _totalLength = _player.CurrentItem.Asset.Duration.Seconds;
                        parentPlayer.SoundLength?.Invoke(this, _totalLength);
                    }
                    StartTimeObserver(parentPlayer);
                    _player.Play();
                };

                parentPlayer.Pause += (sender, innere) =>
                {
                    _player.Pause();
                };

                parentPlayer.Stop += (sender, innere) =>
                {
                    EndTimeObserver();
                    _player.Stop();
                };

                parentPlayer.GoToTime += (sender, sec) =>
                {
                    _player.SeekAsync(CoreMedia.CMTime.FromSeconds(sec, Constants.NSEC_PER_SEC));
                };
            }
        }
        public void SetVideoSurface(IVideoSurface videoSurface)
        {
            var view = ((VideoSurface)videoSurface);

            if (view == null)
            {
                throw new ArgumentException("VideoSurface must be a UIView");
            }
            RenderSurface = videoSurface;
            _videoLayer   = AVPlayerLayer.FromPlayer(Player);
            view.Layer.AddSublayer(_videoLayer);
            _videoLayer.Frame = view.Frame;
            SetAspectMode(VideoAspectMode.AspectFit);
        }
        private void PlatformStop()
        {
            var movieView = _currentVideo.Player;

            movieView.Pause();
            movieView.Seek(CoreMedia.CMTime.Zero);

            nsWindow.ContentView.WillRemoveSubview(view);
            view.RemoveFromSuperview();
            view.Dispose();
            view = null;
            layer.Dispose();
            layer = null;
        }
Exemple #27
0
        public void SetVideoSurface(IVideoSurface videoSurface)
        {
            var view = (VideoSurface)videoSurface;

            if (view == null)
            {
                throw new ArgumentException("VideoSurface must be a UIView");
            }

            RenderSurface            = videoSurface;
            _videoLayer              = AVPlayerLayer.FromPlayer(Player);
            _videoLayer.Frame        = view.Frame;
            _videoLayer.VideoGravity = AVLayerVideoGravity.ResizeAspect;
            view.Layer.AddSublayer(_videoLayer);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            _asset = AVAsset.FromUrl (NSUrl.FromFilename ("sample.m4v"));
            _playerItem = new AVPlayerItem (_asset);

            _player = new AVPlayer (_playerItem);
            _playerLayer = AVPlayerLayer.FromPlayer (_player);
            _playerLayer.Frame = View.Frame;

            View.Layer.AddSublayer (_playerLayer);

            _player.Play ();
        }
Exemple #29
0
 public static void SetPlayerView(this IMediaPlayer mediaPlayer, VideoSurface videoView)
 {
     if (mediaPlayer is IVideoPlayer <AVPlayer, VideoSurface> videoPlayer)
     {
         var layer = AVPlayerLayer.FromPlayer(videoPlayer.Player);
         layer.Frame        = videoView.Frame;
         layer.VideoGravity = AVLayerVideoGravity.ResizeAspect;
         videoView.Layer.AddSublayer(layer);
         videoPlayer.PlayerView = videoView;
     }
     else
     {
         throw new ArgumentException("MediaPlayer needs to be of type IMediaPlayer<SimpleExoPlayer> to use this extension", nameof(mediaPlayer));
     }
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            asset      = AVAsset.FromUrl(NSUrl.FromFilename("sample.m4v"));
            playerItem = new AVPlayerItem(asset);

            player            = new AVPlayer(playerItem);
            playerLayer       = AVPlayerLayer.FromPlayer(player);
            playerLayer.Frame = View.Frame;

            View.Layer.AddSublayer(playerLayer);

            player.Play();
        }
Exemple #31
0
        protected override void OnElementChanged(ElementChangedEventArgs <View> e)
        {
            base.OnElementChanged(e);

            _asset      = AVAsset.FromUrl(NSUrl.FromFilename("intro.mp4"));
            _playerItem = new AVPlayerItem(_asset);

            _player = new AVPlayer(_playerItem);
            _player.ActionAtItemEnd = AVPlayerActionAtItemEnd.None;
            _playerLayer            = AVPlayerLayer.FromPlayer(_player);

            videoEndNotificationToken = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, VideoDidFinishPlaying, _playerItem);

            _player.Play();
        }
        public override void AwakeFromNib()
        {
            base.AwakeFromNib();
            _asset = AVAsset.FromUrl(NSUrl.FromFilename("video.mp4"));
            _playerItem = new AVPlayerItem(_asset);
            _player = new AVPlayer(_playerItem);

            image = new UIImageView(UIImage.FromFile("Icon-76.png"));
            label.Font = UIFont.FromName("Cochin-BoldItalic", 22f);
            label.TextColor = UIColor.FromRGB(127, 51, 0);
            label.BackgroundColor = UIColor.Clear;
            LayoutIfNeeded();
            _playerLayer = AVPlayerLayer.FromPlayer(_player);
            
            _player.ExternalPlaybackVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
        }
        public static AVPlayer ShowVideo(this UIView view, string pathVideo)
        {
            var asset      = AVAsset.FromUrl(NSUrl.FromFilename(pathVideo));
            var playerItem = new AVPlayerItem(asset);

            var player = new AVPlayer(playerItem);

            var playerLayer = AVPlayerLayer.FromPlayer(player);

            playerLayer.Frame = view.Frame;

            view.Layer.AddSublayer(playerLayer);

            player.Play();

            return(player);
        }
Exemple #34
0
        public MyPlayerView(bool noController, RectangleF frame)
        {
            this.Frame = frame;
            if (noController)
            {
                var asset      = AVAsset.FromUrl(NSUrl.FromFilename("sample.m4v"));
                var playerItem = new AVPlayerItem(asset);
                this._MyAvPlayer = new AVPlayer(playerItem);

                var playerLayer = AVPlayerLayer.FromPlayer(this._MyAvPlayer);
                playerLayer.Frame = this.Frame;
                _MyAvPlayer.Play();


                this.Layer.AddSublayer(playerLayer);
            }
        }
Exemple #35
0
 public void DisposeVideoPlayer()
 {
     if (!_playerLoaded || _player == null)
     {
         return;
     }
     if (_positionDisplayTimer != null)
     {
         _positionDisplayTimer.Stop();
     }
     _player.Pause();
     _playerLoaded = false;
     _asset        = null;
     _playerItem   = null;
     _playerLayer  = null;
     _player       = null;
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.


            _asset      = AVAsset.FromUrl(NSUrl.FromFilename("sample.m4v"));
            _playerItem = new AVPlayerItem(_asset);

            _player            = new AVPlayer(_playerItem);
            _playerLayer       = AVPlayerLayer.FromPlayer(_player);
            _playerLayer.Frame = new RectangleF(25, 15, 320 - 15, 240 - 15);

            View.Layer.AddSublayer(_playerLayer);

            _player.Play();
        }
Exemple #37
0
        protected override void OnElementChanged(ElementChangedEventArgs <View> e)
        {
            base.OnElementChanged(e);

            //Get the video
            //bubble up to the AVPlayerLayer
            //var url = new NSUrl ("http://www.androidbegin.com/tutorial/AndroidCommercial.3gp");
            _asset      = AVAsset.FromUrl(NSUrl.FromFilename("explore.mp4"));
            _playerItem = new AVPlayerItem(_asset);

            _player = new AVPlayer(_playerItem);
            _player.ActionAtItemEnd = AVPlayerActionAtItemEnd.None;
            _playerLayer            = AVPlayerLayer.FromPlayer(_player);

            videoEndNotificationToken = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, VideoDidFinishPlaying, _playerItem);

            _player.Play();
        }
		public override void PresentStep (int index, PresentationViewController presentationViewController)
		{
			switch (index) {
			case 0:
				// Set the slide's title and subtitle and add some text
				TextManager.SetTitle ("Materials");
				TextManager.SetSubtitle ("CALayer as texture");

				TextManager.AddCode ("#// Map a layer tree on a 3D object. \n"
				+ "aNode.Geometry.FirstMaterial.Diffuse.#Contents# = #aLayerTree#;#");

				// Add the model
				var intermediateNode = SCNNode.Create ();
				intermediateNode.Position = new SCNVector3 (0, 3.9f, 8);
				intermediateNode.Rotation = new SCNVector4 (1, 0, 0, -(float)(Math.PI / 2));
				GroundNode.AddChildNode (intermediateNode);
				Utils.SCAddChildNode (intermediateNode, "frames", "Scenes/frames/frames", 8);

				presentationViewController.NarrowSpotlight (true);
				break;
			case 1:
				SCNTransaction.Begin ();
				SCNTransaction.AnimationDuration = 1;
						
				// Change the point of view to "frameCamera" (a camera defined in the "frames" scene)
				var frameCamera = ContentNode.FindChildNode ("frameCamera", true);
				((SCNView)presentationViewController.View).PointOfView = frameCamera;

				// The "frames" scene contains animations, update the end time of our main scene and start to play the animations
				((SCNView)presentationViewController.View).Scene.SetAttribute (new NSNumber (7.33f), SCNScene.EndTimeAttributeKey);
				((SCNView)presentationViewController.View).CurrentTime = 0;
				((SCNView)presentationViewController.View).Playing = true;
				((SCNView)presentationViewController.View).Loops = true;

				PlayerLayer1 = ConfigurePlayer (NSBundle.MainBundle.PathForResource ("Movies/movie1", "mov"), "PhotoFrame-Vertical");
				PlayerLayer2 = ConfigurePlayer (NSBundle.MainBundle.PathForResource ("Movies/movie2", "mov"), "PhotoFrame-Horizontal");

				SCNTransaction.Commit ();
				break;
			}
		}
        public void Open(string videoFileName)
        {
            _playerLoaded = false;
            if (_player != null)
            {
                try
                {
                    _player.Pause();
                    _player.Dispose();
                    _player = null;
                    foreach (var subView in View.VideoView.Subviews)
                    {
                        subView.RemoveFromSuperview();
                    }
                    foreach (var subLayer in View.VideoView.Layer.Sublayers)
                    {
                        subLayer.RemoveFromSuperLayer();
                    }
                    _playerLayer.Dispose();
                    _playerItem.Dispose();
                    _asset.Dispose();
                }
                catch
                {
                }
            }
            ShowPlayImage(false);
            _asset = AVAsset.FromUrl(NSUrl.FromFilename(videoFileName));
            _playerItem = new AVPlayerItem(_asset);
            _player = new AVPlayer(_playerItem);
            _playerLayer = AVPlayerLayer.FromPlayer(_player);
            _videoView = new NSMyVideoView(new CoreGraphics.CGRect(0, 0, View.VideoView.Frame.Width, View.VideoView.Frame.Width), View.VideoView, _playerLayer);
            _videoView.WantsLayer = true;
            View.VideoView.AddSubview(_videoView);
            View.VideoView.WantsLayer = true;
            _playerLayer.Frame = View.VideoView.Bounds;
            View.VideoView.Layer.AddSublayer(_playerLayer);
           _videoView.ResizeWithCorrectAspectRatio();
            _playerLoaded = true;

        }
 public void DisposeVideoPlayer()
 {
     if (!_playerLoaded || _player == null)
     {
         return;
     }
     if (_positionDisplayTimer != null)
     {
         _positionDisplayTimer.Stop();
     }
     _player.Pause();
     _playerLoaded = false;
     _asset = null;
     _playerItem = null;
     _playerLayer = null;
     _player = null;
 }
		public void PhotoLibraryDidChange (PHChange changeInstance)
		{
			// Call might come on any background queue. Re-dispatch to the main queue to handle it.
			DispatchQueue.MainQueue.DispatchAsync (() => {
				// Check if there are changes to the asset we're displaying.
				PHObjectChangeDetails changeDetails = changeInstance.GetObjectChangeDetails (Asset);
				if (changeDetails == null)
					return;

				// Get the updated asset.
				// TODO: check return type. Catch! ObjectAfterChanges should be PHObject instead of NSObject https://bugzilla.xamarin.com/show_bug.cgi?id=35540
				Asset = (PHAsset)changeDetails.ObjectAfterChanges;
				if(Asset != null)
					FavoriteButton.Title = Asset.Favorite ? "♥︎" : "♡";

				// If the asset's content changed, update the image and stop any video playback.
				if (changeDetails.AssetContentChanged) {
					UpdateImage ();

					playerLayer?.RemoveFromSuperLayer ();
					playerLayer = null;
				}
			});
		}
        private void InitializePlayer()
        {
            _player = new AVPlayer();
            _videoLayer = AVPlayerLayer.FromPlayer(_player);

            NSError activationError = null;
            if (activationError != null)
                Console.WriteLine("Could not activate audio session {0}", activationError.LocalizedDescription);

            Player.AddPeriodicTimeObserver(new CMTime(1, 4), DispatchQueue.MainQueue, delegate
            {
                var totalDuration = TimeSpan.FromSeconds(_player.CurrentItem.Duration.Seconds);
                var totalProgress = Position.TotalMilliseconds /
                                    totalDuration.TotalMilliseconds;
                PlayingChanged?.Invoke(this, new PlayingChangedEventArgs(totalProgress, Position, Duration));
            });
        }
		partial void PlayButtonClickHandler (NSObject sender)
		{
			if (LivePhotoView.LivePhoto != null) {
				// We're displaying a live photo, begin playing it.
				LivePhotoView.StartPlayback (PHLivePhotoViewPlaybackStyle.Full);
			} else if (playerLayer != null) {
				// An AVPlayerLayer has already been created for this asset.
				playerLayer.Player.Play ();
			} else {
				// Request an AVAsset for the PHAsset we're displaying.
				PHImageManager.DefaultManager.RequestAvAsset (Asset, null, (asset, audioMix, info) =>
					DispatchQueue.MainQueue.DispatchAsync (() => {
						if (playerLayer == null) {
							CALayer viewLayer = View.Layer;

							// Create an AVPlayerItem for the AVAsset.
							var playerItem = new AVPlayerItem (asset);
							playerItem.AudioMix = audioMix;

							// Create an AVPlayer with the AVPlayerItem.
							var player = new AVPlayer (playerItem);

							// Create an AVPlayerLayer with the AVPlayer.
							playerLayer = AVPlayerLayer.FromPlayer (player);

							// Configure the AVPlayerLayer and add it to the view.
							playerLayer.VideoGravity = AVLayerVideoGravity.ResizeAspect;
							playerLayer.Frame = new CGRect (0, 0, viewLayer.Bounds.Width, viewLayer.Bounds.Height);

							viewLayer.AddSublayer (playerLayer);
							playerLayer.Player.Play ();
						}
				}));
			}
		}
		private void initializeVideo()
		{
			var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
			var library = System.IO.Path.Combine (documents, "..", "Library");
			var urlpath = System.IO.Path.Combine (library, "sweetMovieFilm.mov");

			url = new NSUrl (urlpath, false);

			_asset = AVAsset.FromUrl(url);
			_playerItem = new AVPlayerItem (_asset);


			_player = new AVPlayer (_playerItem);

			_notificationHandle = NSNotificationCenter.DefaultCenter.AddObserver (AVPlayerItem.DidPlayToEndTimeNotification, VideoDonePlaying);


			_playerLayer = AVPlayerLayer.FromPlayer (_player);
			_playerLayer.Frame = View.Frame;

		}
Exemple #45
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
			
            
            if (((MissionViewModel)ViewModel).Mission.LiveStream)
            {
                chatView.Hidden = false;
                messageField.Hidden = false;
                sendButton.Hidden = false;
                
                firstTitle.Hidden = true;
                secondTitle.Hidden = true;
                imageView.Hidden = true;
                
                var streamingUri = ((MissionViewModel)ViewModel).LiveStreamViewModel.LiveStreamUrl;
                
                _asset = AVAsset.FromUrl(NSUrl.FromString(streamingUri));
                _playerItem = new AVPlayerItem(_asset);
                
                _player = new AVPlayer(_playerItem);

                _playerLayer = AVPlayerLayer.FromPlayer(_player);
                _playerLayer.Frame = new RectangleF(21, 88, 602, 311);
                View.Layer.AddSublayer(_playerLayer);
                _player.Play();
                
                ((MissionViewModel)ViewModel).LiveStreamViewModel.UserName = "******";
                
                chatView.Text = "";
                
                var previousText = string.Empty;
                
                SunnySocket.MessageReceivedAsyncCallback = (string name, string message) =>
                InvokeOnMainThread(() =>
                {
                    if (message != previousText)
                    {
                        chatView.Text = name + " - " + message + "\n" + chatView.Text;
                        chatView.Font = UIFont.FromName("HelveticaNeue-Bold", 15);
                        chatView.TextColor = UIColor.FromRGBA(0.027f, 0.102f, 0.389f, 1.000f);
                        previousText = message;
                    }
                });
                
                messageField.ShouldReturn += (x) =>
                {
                    ((MissionViewModel)ViewModel).LiveStreamViewModel.SendMessageCommand.Execute(null); 
                    return true;
                };
                    
                var set = this.CreateBindingSet<MissionView, MissionViewModel>();
                set.Bind(title).To(vm => vm.Mission.Name);
                set.Bind(messageField).To(vm => vm.LiveStreamViewModel.Message);
                set.Bind(backButton).To("GoBackCommand"); 
                set.Bind(sendButton).To("LiveStreamViewModel.SendMessageCommand"); 
                set.Apply();
                
                messageField.BecomeFirstResponder();
            }
            else
            {
                chatView.Hidden = true;
                messageField.Hidden = true;
                sendButton.Hidden = true;
                
                var imageBorder = new UIButton(UIButtonType.System);
                imageBorder.Frame = new RectangleF(imageView.Frame.X - 1, imageView.Frame.Y - 1, imageView.Frame.Width + 2, imageView.Frame.Height + 2);
                imageBorder.BackgroundColor = UIColor.Clear;
                imageBorder.Layer.BorderColor = UIColor.FromRGBA(0.631f, 0.816f, 0.922f, 1.000f).CGColor;
                imageBorder.Layer.CornerRadius = 4;
                imageBorder.Layer.BorderWidth = 1;
                View.AddSubview(imageBorder);
            
                var webview = new UIWebView();
                webview.Frame = new RectangleF(450, 87, 554, 681);
            
                var webviewBorder = new UIButton(UIButtonType.System);
                webviewBorder.Frame = new RectangleF(webview.Frame.X - 1, webview.Frame.Y - 1, webview.Frame.Width + 2, webview.Frame.Height + 2);
                webviewBorder.BackgroundColor = UIColor.Clear;
                webviewBorder.Layer.BorderColor = UIColor.FromRGBA(0.631f, 0.816f, 0.922f, 1.000f).CGColor;
                webviewBorder.Layer.CornerRadius = 4;
                webviewBorder.Layer.BorderWidth = 1;
                View.AddSubview(webviewBorder);
            
                View.AddSubview(webview);
            
                var newsButton = new UIButton(UIButtonType.System);
                newsButton.Frame = new RectangleF(21, 485, 360, 60);
                newsButton.BackgroundColor = UIColor.Clear;
                newsButton.Layer.BorderColor = UIColor.FromRGBA(0.631f, 0.816f, 0.922f, 1.000f).CGColor;
                newsButton.Layer.CornerRadius = 4;
                newsButton.Layer.BorderWidth = 1;
                View.AddSubview(newsButton);

       
                var notifyButton = new UIButton(UIButtonType.System);
                notifyButton.Frame = new RectangleF(21, 605, 360, 60);
                notifyButton.BackgroundColor = UIColor.Clear;
                notifyButton.Layer.BorderColor = UIColor.FromRGBA(0.631f, 0.816f, 0.922f, 1.000f).CGColor;
                notifyButton.Layer.CornerRadius = 4;
                notifyButton.Layer.BorderWidth = 1;
                View.AddSubview(notifyButton);

                notifyButton.TouchUpInside += (sender, e) =>
                {
                    notifyButton.Enabled = false;
                    new UIAlertView("Thank you", "You'll receive a notification when we go fly fly (or boom boom)", null, "Ok").Show();
                };
            
                var imageViewLoader = new MvxImageViewLoader(() => this.imageView);
                        
                var set = this.CreateBindingSet<MissionView, MissionViewModel>();
                set.Bind(imageViewLoader).To(vm => vm.Mission.ImageUri);
                set.Bind(title).To(vm => vm.Mission.Name);
                set.Bind(newsButton).To("ShowMissionNewsOverviewCommand");
                set.Bind(notifyButton).To("InitPushCommand"); 
                set.Bind(backButton).To("GoBackCommand"); 
                set.Apply();
            
                var html = ((MissionViewModel)ViewModel).Mission.Text;
                webview.LoadHtmlString(html, null);     
            
                webview.ShouldStartLoad += shouldStartLoad; 
            }
                   
        }
        private void InitializePlayer()
        {
            _player = new AVPlayer();
            _videoLayer = AVPlayerLayer.FromPlayer(_player);
            var avSession = AVAudioSession.SharedInstance();

            // By setting the Audio Session category to AVAudioSessionCategorPlayback, audio will continue to play when the silent switch is enabled, or when the screen is locked.
            avSession.SetCategory(AVAudioSessionCategory.Playback);

            NSError activationError = null;
            avSession.SetActive(true, out activationError);
            if (activationError != null)
                Console.WriteLine("Could not activate audio session {0}", activationError.LocalizedDescription);

            Player.AddPeriodicTimeObserver(new CMTime(1, 4), DispatchQueue.MainQueue, delegate
            {
                var totalDuration = TimeSpan.FromSeconds(_player.CurrentItem.Duration.Seconds);
                var totalProgress = Position.TotalMilliseconds /
                                    totalDuration.TotalMilliseconds;
                PlayingChanged?.Invoke(this, new PlayingChangedEventArgs(totalProgress, Position, Duration));
            });
        }
		partial void Play (NSObject sender)
		{
			// An AVPlayerLayer has already been created for this asset; just play it.
			if (playerLayer != null) {
				playerLayer.Player.Play ();
			} else {
				// Request an AVAsset for the displayed PHAsset and set up a layer for playing it.
				PHImageManager.DefaultManager.RequestAvAsset (Asset, null, (avAsset, audioMix, info) => {
					DispatchQueue.MainQueue.DispatchSync (() => {
						if (playerLayer != null)
							return;

						// Create an AVPlayerItem for the AVAsset.
						var playerItem = new AVPlayerItem (avAsset);
						playerItem.AudioMix = audioMix;

						// Create an AVPlayer with the AVPlayerItem.
						var player = new AVPlayer (playerItem);
						// Create an AVPlayerLayer with the AVPlayer.
						var layer = AVPlayerLayer.FromPlayer (player);
						layer.VideoGravity = AVLayerVideoGravity.ResizeAspect;
						layer.Frame = View.Layer.Bounds;
						View.Layer.AddSublayer (layer);

						player.Play ();

						// Refer to the player layer so we can remove it later.
						playerLayer = layer;
					});
				});
			}
		}