Ejemplo n.º 1
0
        public void InitFile(string pathToAudioFile)
        {
            if (Player != null)
            {
                Stop();
                IsStoped    = true;
                IsCompleted = true;
            }

            if (string.IsNullOrWhiteSpace(pathToAudioFile))
            {
                throw new Exception("No file specified to play");
            }
            //http://192.168.0.95:50000/api/Post/GetFileByName?fileName=2556bc1b-f6e7-4bd8-8984-d046b677ccf2&type=2
            using (var url = NSUrl.FromString(pathToAudioFile))
            {
                var testURL = NSUrl.FromString("https://s3.amazonaws.com/kargopolov/kukushka.mp3");
                PlayerItem = AVPlayerItem.FromUrl(url);
                if (Player == null)
                {
                    Player = new AVPlayer(PlayerItem);
                    if (Player == null)
                    {
                        return;
                    }
                }
                videoEndNotificationToken = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, VideoDidFinishPlaying, PlayerItem);
            }
        }
        /// <summary>
        /// Updates the video source property on the native player.
        /// </summary>
        /// <param name="oldElement">The old element.</param>
        private async Task UpdateSource(VideoPlayer oldElement = null)
        {
            try
            {
                var newSource = Element?.Source;

                if (oldElement != null)
                {
                    var oldSource = oldElement.Source;

                    if (!oldSource.Equals(newSource))
                    {
                        return;
                    }
                }

                Element.SetValue(VideoPlayer.IsLoadingPropertyKey, true);
                var videoSourceHandler = VideoSourceHandler.Create(newSource);
                var path = await videoSourceHandler.LoadVideoAsync(newSource, new CancellationToken());

                Log.Info($"Video Source: {path}");

                if (!string.IsNullOrEmpty(path))
                {
                    if (_currentTimeObserver != null)
                    {
                        _playerControl.Player.RemoveTimeObserver(_currentTimeObserver);
                    }
                    if (_didPlayToEndTimeNotificationObserver != null)
                    {
                        NSNotificationCenter.DefaultCenter.RemoveObserver(_didPlayToEndTimeNotificationObserver);
                    }

                    // Update video source.
                    Element.SetValue(VideoPlayer.CurrentTimePropertyKey, TimeSpan.Zero);

                    var pathUrl = newSource is UriVideoSource?NSUrl.FromString(path) : NSUrl.FromFilename(path);

                    _playerControl.Player.CurrentItem?.RemoveObserver(FromObject(this), "status");

                    _playerControl.Player.ReplaceCurrentItemWithPlayerItem(AVPlayerItem.FromUrl(pathUrl));

                    _playerControl.Player.CurrentItem.AddObserver(this, (NSString)"status", 0, Handle);

                    Element.OnPlayerStateChanged(CreateVideoPlayerStateChangedEventArgs(PlayerState.Initialized));

                    _didPlayToEndTimeNotificationObserver = NSNotificationCenter.DefaultCenter.AddObserver(
                        AVPlayerItem.DidPlayToEndTimeNotification, DidPlayToEndTimeNotification, _playerControl.Player.CurrentItem);

                    _currentTimeObserver = _playerControl.Player.AddPeriodicTimeObserver(CMTime.FromSeconds(1, 1), null,
                                                                                         time => Element?.SetValue(VideoPlayer.CurrentTimePropertyKey,
                                                                                                                   double.IsNaN(time.Seconds) ? TimeSpan.Zero : TimeSpan.FromSeconds(time.Seconds)));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Element.SetValue(VideoPlayer.IsLoadingPropertyKey, false);
            }
        }
 // Play song from persistentSongID
 public void playSong(Song song)
 {
     currentSong = song;
     if (song.streamingURL == null)
     {
         MusicQuery  musicQuery = new MusicQuery();
         MPMediaItem mediaItem  = musicQuery.queryForSongWithId(song.songID);
         if (mediaItem != null)
         {
             NSUrl Url = mediaItem.AssetURL;
             item = AVPlayerItem.FromUrl(Url);
             if (item != null)
             {
                 this.avPlayer.ReplaceCurrentItemWithPlayerItem(item);
             }
             MPNowPlayingInfo np = new MPNowPlayingInfo();
             SetNowPlayingInfo(song, np);
             this.play();
         }
     }
     else
     {
         NSUrl nsUrl = NSUrl.FromString(song.streamingURL);
         MyMusicPlayer.myMusicPlayer?.streamingItem?.RemoveObserver(MyMusicPlayer.myMusicPlayer, "status");
         streamingItem = AVPlayerItem.FromUrl(nsUrl);
         streamingItem.AddObserver(this, new NSString("status"), NSKeyValueObservingOptions.New, avPlayer.Handle);
         avPlayer.ReplaceCurrentItemWithPlayerItem(streamingItem);
         streamingItemPaused = false;
         //NSNotificationCenter.DefaultCenter.AddObserver(this, new Selector("playerItemDidReachEnd:"), AVPlayerItem.DidPlayToEndTimeNotification, streamingItem);
     }
 }
Ejemplo n.º 4
0
        private void PlatformInitialize()
        {
            var err = new NSError();

            movie  = AVPlayerItem.FromUrl(NSUrl.FromFilename(FileName));
            Player = new AVPlayer(movie);
        }
Ejemplo n.º 5
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;
            }
        }
Ejemplo n.º 6
0
 public void ReplaceCurrentItem(NSUrl url)
 {
     if (CurrentItem != null)
     {
         CurrentItem.RemoveObserver(this, new NSString("status"));
         CurrentItem.RemoveObserver(this, new NSString("rate"));
     }
     streamingItem = AVPlayerItem.FromUrl(url);
     streamingItem.AddObserver(this, new NSString("rate"), 0, new IntPtr(0));
     streamingItem.AddObserver(this, new NSString("status"), 0, new IntPtr(0));
     ReplaceCurrentItemWithPlayerItem(streamingItem);
 }
Ejemplo n.º 7
0
        public override async Task <bool> PrepareData(PlaybackData data, bool isPlaying)
        {
            playbackData = data;
            stateObserver?.Dispose();
            stateObserver = null;
            CurrentSongId = data.SongId;
            AVPlayerItem playerItem       = null;
            var          songPlaybackData = data.SongPlaybackData;

            if (songPlaybackData.IsLocal || songPlaybackData.CurrentTrack.ServiceType == MusicPlayer.Api.ServiceType.iPod)
            {
                if (songPlaybackData.Uri == null)
                {
                    return(false);
                }
                var url = string.IsNullOrWhiteSpace(songPlaybackData?.CurrentTrack?.FileLocation) ? new NSUrl(songPlaybackData.Uri.AbsoluteUri) : NSUrl.FromFilename(songPlaybackData.CurrentTrack.FileLocation);
                playerItem = AVPlayerItem.FromUrl(url);
                await playerItem.WaitStatus();
            }
            else
            {
#if HttpPlayback
                var urlEndodedSongId = HttpUtility.UrlEncode(data.SongId);
                var url = $"http://localhost:{LocalWebServer.Shared.Port}/api/GetMediaStream/Playback?SongId={urlEndodedSongId}";
                playerItem = AVPlayerItem.FromUrl(new NSUrl(url));
#else
                NSUrlComponents comp =
                    new NSUrlComponents(
                        NSUrl.FromString(
                            $"http://localhost/{songPlaybackData.CurrentTrack.Id}.{data.SongPlaybackData.CurrentTrack.FileExtension}"), false);
                comp.Scheme = "streaming";
                if (comp.Url != null)
                {
                    var asset = new AVUrlAsset(comp.Url, new NSDictionary());
                    asset.ResourceLoader.SetDelegate(resourceDelegate, DispatchQueue.MainQueue);
                    playerItem    = new AVPlayerItem(asset, (NSString)"duration");
                    stateObserver = playerItem.AddObserver("status", NSKeyValueObservingOptions.New, (obj) =>
                    {
                        if (shouldBePlaying)
                        {
                            player.Play();
                        }
                        Console.WriteLine($"Player Status {playerItem.Status}");
                    });
                }
#endif
            }
            player.ReplaceCurrentItemWithPlayerItem(playerItem);
            IsPrepared = true;

            return(true);
        }
Ejemplo n.º 8
0
        public void TestLoopingEnabled()
        {
            string file = Path.Combine(NSBundle.MainBundle.ResourcePath, "Hand.wav");

            Assert.True(File.Exists(file), file);
            using (var url = new NSUrl(file))
                using (var playerItem = AVPlayerItem.FromUrl(url))
                    using (AVQueuePlayer player = AVQueuePlayer.FromItems(new[] { playerItem }))
                        using (var playerLooper = AVPlayerLooper.FromPlayer(player, playerItem)) {
                            Assert.True(playerLooper.LoopingEnabled, "The default value should be true.");
                            playerLooper.DisableLooping();
                            Assert.False(playerLooper.LoopingEnabled, "Looping enabled should return false after 'DisableLooping'");
                        }
        }
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);
            playPauseButton.UserInteractionEnabled = false;
            playPauseButton.TintColor = UIColor.LightGray;
            // try different approach
            NSUrl url = NSUrl.FromString("http://ccmixter.org/content/bradstanfield/bradstanfield_-_People_Let_s_Stop_The_War.mp3");

            streamingItem = AVPlayerItem.FromUrl(url);
            player        = AVPlayer.FromPlayerItem(streamingItem);
            streamingItem.AddObserver(this, new NSString("status"), NSKeyValueObservingOptions.Initial, player.Handle);
            //NSNotificationCenter.DefaultCenter.AddObserver(this, new Selector("playerItemDidReachEnd:"), AVPlayerItem.DidPlayToEndTimeNotification, streamingItem);

            Title = "Streaming";
            playPauseButton.TitleLabel.Text = "Pause";
            timeLabel.Text = string.Empty;

            UIApplication.SharedApplication.BeginReceivingRemoteControlEvents();
            this.BecomeFirstResponder();
        }
Ejemplo n.º 10
0
        public override async Task <bool> PrepareData(PlaybackData data, bool isPlaying)
        {
            CurrentSongId = data.SongId;
            AVPlayerItem playerItem   = null;
            var          playbackData = data.SongPlaybackData;

            if (playbackData.IsLocal || playbackData.CurrentTrack.ServiceType == MusicPlayer.Api.ServiceType.iPod)
            {
                if (playbackData.Uri == null)
                {
                    return(false);
                }
                var url = string.IsNullOrWhiteSpace(playbackData?.CurrentTrack?.FileLocation) ? new NSUrl(playbackData.Uri.AbsoluteUri) : NSUrl.FromFilename(playbackData.CurrentTrack.FileLocation);
                playerItem = AVPlayerItem.FromUrl(url);
                await playerItem.WaitStatus();
            }
            else
            {
#if HttpPlayback
                var urlEndodedSongId = HttpUtility.UrlEncode(data.SongId);
                var url = $"http://localhost:{LocalWebServer.Shared.Port}/api/GetMediaStream/Playback?SongId={urlEndodedSongId}";
                playerItem = AVPlayerItem.FromUrl(new NSUrl(url));
#else
                NSUrlComponents comp =
                    new NSUrlComponents(
                        NSUrl.FromString(
                            $"http://localhost/{playbackData.CurrentTrack.Id}.{data.SongPlaybackData.CurrentTrack.FileExtension}"), false);
                comp.Scheme = "streaming";
                if (comp.Url != null)
                {
                    var asset = new AVUrlAsset(comp.Url, new NSDictionary());
                    asset.ResourceLoader.SetDelegate(NativeAudioPlayer.LoaderDelegate, DispatchQueue.MainQueue);
                    playerItem = new AVPlayerItem(asset);
                }
#endif
            }
            player.ReplaceCurrentItemWithPlayerItem(playerItem);
            IsPrepared = true;
            return(true);
        }
Ejemplo n.º 11
0
 private void PlatformInitialize(NSUrl url)
 {
     _sound            = AVPlayerItem.FromUrl(url);
     _player           = AVPlayer.FromPlayerItem(_sound);
     playToEndObserver = AVPlayerItem.Notifications.ObserveDidPlayToEndTime(OnFinishedPlaying);
 }
Ejemplo n.º 12
0
        private void UpdatePlaying()
        {
            if (!isPlaying)
            {
                if (player == null)
                {
                    playerItem = AVPlayerItem.FromUrl(NSUrl.FromString(slider.FileUrl));// (asset);

                    player = new AVPlayer(playerItem);

                    slider.TimeLeftString = "loading...";
                    AVAudioSession.SharedInstance().SetCategory(AVAudioSessionCategory.Playback);
                    var interval = new CMTime(1, 1);
                    player.ActionAtItemEnd = AVPlayerActionAtItemEnd.None;
                    var videoEndNotificationToken = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, VideoDidFinishPlaying, playerItem);
                    if (valueToSeekIfNotPlaing.HasValue)
                    {
                        var duration = slider.FileDuration;
                        if (duration.HasValue)
                        {
                            var totalSeconds = TimeSpan.FromMilliseconds(duration.Value).TotalSeconds;
                            var value        = valueToSeekIfNotPlaing.Value * totalSeconds;
                            var seekTime     = new CMTime((long)value, 1);

                            Seek(seekTime, totalSeconds, value, false);
                        }
                    }

                    /* do
                     *                   {
                     *                           await Task.Delay(5);
                     *                   } while (player.Status != AVPlayerStatus.ReadyToPlay);
                     */
                    player.AddPeriodicTimeObserver(interval, DispatchQueue.MainQueue, delegate(CMTime time)
                    {
                        var duration = slider.FileDuration;
                        if (duration.HasValue)
                        {
                            var totalSeconds      = TimeSpan.FromMilliseconds(duration.Value).TotalSeconds;
                            var seconds           = time.Seconds;
                            var leftTime          = totalSeconds - seconds;
                            slider.Value          = (float)(seconds / totalSeconds);
                            slider.TimeLeftString = TimeSpan.FromSeconds(leftTime).ToString(@"mm\:ss");
                            if (Control != null)
                            {
                                Control.Value = (float)(seconds / totalSeconds);
                            }
                        }
                    });
                }

                slider.CommandText = "Pause";
                //audioSlider.BackgroundColor = Color.GreenYellow;
                slider.CommandImageFileName = slider.PauseImageFileName;
                isPlaying = true;
                player.Play();
            }
            else
            {
                slider.CommandImageFileName = slider.PlayImageFileName;
                slider.CommandText          = "Play";

                //button.SetTitle("paused", UIControlState.Normal);
                player.Pause();
                isPlaying = false;
            }
        }
Ejemplo n.º 13
0
        async Task <Tuple <bool, AVPlayerItem> > prepareSong(Song song, bool playVideo = false)
        {
            try
            {
                isVideo = playVideo;
                LogManager.Shared.Log("Preparing Song", song);
                var data         = GetPlaybackData(song.Id);
                var playbackData = await MusicManager.Shared.GetPlaybackData(song, playVideo);

                if (playbackData == null)
                {
                    return(new Tuple <bool, AVPlayerItem>(false, null));
                }
                if (data.CancelTokenSource.IsCancellationRequested)
                {
                    return(new Tuple <bool, AVPlayerItem>(false, null));
                }

                AVPlayerItem playerItem = null;

                if (song == CurrentSong)
                {
                    Settings.CurrentTrackId = playbackData.CurrentTrack.Id;
                    isVideo = playbackData.CurrentTrack.MediaType == MediaType.Video;
                    Settings.CurrentPlaybackIsVideo = isVideo;
                    NotificationManager.Shared.ProcVideoPlaybackChanged(isVideo);
                }
                if (playbackData.IsLocal || playbackData.CurrentTrack.ServiceType == MusicPlayer.Api.ServiceType.iPod)
                {
                    if (playbackData.Uri == null)
                    {
                        return(new Tuple <bool, AVPlayerItem>(false, null));
                    }
                    LogManager.Shared.Log("Local track found", song);
                    var url = string.IsNullOrWhiteSpace(playbackData?.CurrentTrack?.FileLocation) ? new NSUrl(playbackData.Uri.AbsoluteUri) : NSUrl.FromFilename(playbackData.CurrentTrack.FileLocation);
                    playerItem = AVPlayerItem.FromUrl(url);
                    await playerItem.WaitStatus();

                    NotificationManager.Shared.ProcSongDownloadPulsed(song.Id, 1f);
                }
                else
                {
                    data.SongPlaybackData = playbackData;
                    data.DownloadHelper   = await DownloadManager.Shared.DownloadNow(playbackData.CurrentTrack.Id, playbackData.Uri);

                    if (data.CancelTokenSource.IsCancellationRequested)
                    {
                        return(new Tuple <bool, AVPlayerItem>(false, null));
                    }
                    LogManager.Shared.Log("Loading online Track", data.SongPlaybackData.CurrentTrack);
                    SongIdTracks[data.SongPlaybackData.CurrentTrack.Id] = song.Id;
                    NSUrlComponents comp =
                        new NSUrlComponents(
                            NSUrl.FromString(
                                $"http://localhost/{playbackData.CurrentTrack.Id}.{data.SongPlaybackData.CurrentTrack.FileExtension}"), false);
                    comp.Scheme = "streaming";
                    if (comp.Url != null)
                    {
                        var asset = new AVUrlAsset(comp.Url, new NSDictionary());
                        asset.ResourceLoader.SetDelegate(LoaderDelegate, DispatchQueue.MainQueue);
                        playerItem = new AVPlayerItem(asset);
                    }
                    if (data.CancelTokenSource.IsCancellationRequested)
                    {
                        return(new Tuple <bool, AVPlayerItem>(false, null));
                    }

                    await playerItem.WaitStatus();
                }
                lastSeconds = -1;
                var success = !data.CancelTokenSource.IsCancellationRequested;

                return(new Tuple <bool, AVPlayerItem>(true, playerItem));
            }
            catch (Exception ex)
            {
                LogManager.Shared.Report(ex);
                return(new Tuple <bool, AVPlayerItem>(false, null));
            }
        }
Ejemplo n.º 14
0
 public void SetData(Constants.ContentType type, string source)
 {
     _contentType = type;
     _soundUrl    = _contentType == Constants.ContentType.Remote ? new NSUrl(source) : new NSUrl(source, false);
     _player.ReplaceCurrentItemWithPlayerItem(AVPlayerItem.FromUrl(_soundUrl));
 }
        /*
         *      MPMoviePlayerController _player;
         *      private List<NSObject> _observers = new List<NSObject>();
         *      protected override void OnElementChanged(ElementChangedEventArgs<CustomVideoSlider> e)
         *      {
         *          base.OnElementChanged(e);
         *          if (e.NewElement != null)
         *          {
         *              if (base.Control == null)
         *              {
         *                  _player = new MPMoviePlayerController();
         *                  _player.ScalingMode = MPMovieScalingMode.AspectFit;
         *
         *                  _player.ShouldAutoplay = true;
         *                  _player.ControlStyle = MPMovieControlStyle.None;
         *                  _player.MovieControlMode=MPMovieControlMode.Hidden;
         *                  _player.View.Frame = this.Bounds;
         *                  _player.BackgroundColor = UIColor.Clear;
         *                  base.SetNativeControl(_player.View);
         *                  var center = NSNotificationCenter.DefaultCenter;
         *                 // _observers.Add(center.AddObserver((NSString)"UIDeviceOrientationDidChangeNotification", DeviceRotated));
         *                  _observers.Add(center.AddObserver(MPMoviePlayerController.PlaybackStateDidChangeNotification, OnLoadStateChanged));
         *                  _observers.Add(center.AddObserver(MPMoviePlayerController.PlaybackDidFinishNotification, OnPlaybackComplete));
         *                  _observers.Add(center.AddObserver(MPMoviePlayerController.WillExitFullscreenNotification, OnExitFullscreen));
         *                  _observers.Add(center.AddObserver(MPMoviePlayerController.WillEnterFullscreenNotification, OnEnterFullscreen));
         *
         *
         *
         *                  bootomToolbarView = new UIView()
         *                  {
         *                      TranslatesAutoresizingMaskIntoConstraints = false,
         *                  };
         *
         *                  bootomToolbarView.AddObserver(this, (NSString)"bounds", NSKeyValueObservingOptions.New, IntPtr.Zero);
         *
         *                  gradientLayer = new CAGradientLayer();
         *                  //gradientLayer.Frame = Bounds;
         *                  gradientLayer.Colors = new CGColor[] { UIColor.Clear.CGColor, UIColor.Orange.CGColor };
         *                  gradientLayer.Locations= new NSNumber[2] {new NSNumber(0.7),new NSNumber(1.2)};
         *                  bootomToolbarView.Layer.AddSublayer(gradientLayer);
         *                  this.InsertSubviewAbove(bootomToolbarView, _player.View);
         *
         *                  labelTimeLeft = new UILabel()
         *                  {
         *                      TranslatesAutoresizingMaskIntoConstraints = false,
         *                      Text = string.Format("{0:mm\\:ss}", TimeSpan.FromMilliseconds(slider.FileDuration ?? 0)),
         *                      TextColor = UIColor.White
         *                  };
         *                  bootomToolbarView.AddSubview(labelTimeLeft);
         *
         *                  labelTimePlayed = new UILabel()
         *                  {
         *                      TranslatesAutoresizingMaskIntoConstraints = false,
         *                      Text = "00:00",
         *                      TextColor = UIColor.White
         *                  };
         *
         *                  bootomToolbarView.AddSubview(labelTimePlayed);
         *
         *                  seekBar = new UISlider()
         *                  {
         *                      TranslatesAutoresizingMaskIntoConstraints = false,
         *                  MaximumTrackTintColor = Color.LightGray.ToUIColor(),
         *                  MinimumTrackTintColor = Color.White.ToUIColor(),
         *                  ThumbTintColor = Color.FromHex("#827DCE").ToUIColor()
         *
         *              };
         *
         *                  seekBar.TouchDown += Control_TouchDown;
         *                  seekBar.TouchUpInside += Control_TouchUpInside;
         *
         *                  bootomToolbarView.AddSubview(seekBar);
         *
         *                  bootomToolbarView.RightAnchor.ConstraintEqualTo(RightAnchor).Active = true;
         *                  bootomToolbarView.LeftAnchor.ConstraintEqualTo(LeftAnchor).Active = true;
         *                  bootomToolbarView.BottomAnchor.ConstraintEqualTo(BottomAnchor).Active = true;
         *                  bootomToolbarView.HeightAnchor.ConstraintEqualTo(40).Active = true;
         *
         *
         *                  labelTimeLeft.RightAnchor.ConstraintEqualTo(bootomToolbarView.RightAnchor, -10).Active = true;
         *                  labelTimeLeft.BottomAnchor.ConstraintEqualTo(bootomToolbarView.BottomAnchor, -10).Active = true;
         *                  labelTimeLeft.WidthAnchor.ConstraintEqualTo(50).Active = true;
         *                  labelTimeLeft.HeightAnchor.ConstraintEqualTo(20).Active = true;
         *
         *                  labelTimePlayed.LeftAnchor.ConstraintEqualTo(bootomToolbarView.LeftAnchor, 10).Active = true;
         *                  labelTimePlayed.BottomAnchor.ConstraintEqualTo(bootomToolbarView.BottomAnchor, -10).Active = true;
         *                  labelTimePlayed.WidthAnchor.ConstraintEqualTo(50).Active = true;
         *                  labelTimePlayed.HeightAnchor.ConstraintEqualTo(20).Active = true;
         *
         *                  seekBar.LeftAnchor.ConstraintEqualTo(labelTimePlayed.RightAnchor, 10).Active = true;
         *                  seekBar.RightAnchor.ConstraintEqualTo(labelTimeLeft.LeftAnchor, -10).Active = true;
         *                  seekBar.BottomAnchor.ConstraintEqualTo(bootomToolbarView.BottomAnchor, -10).Active = true;
         *                  seekBar.HeightAnchor.ConstraintEqualTo(20).Active = true;
         *
         *                  ToggleFullscreen();
         *              }
         *          }
         *          updateVideoPath();
         *          updateFullscreen();
         *      }
         *      private void DeviceRotated(NSNotification notification)
         *      {
         *          ToggleFullscreen();
         *      }
         *
         *      private void OnLoadStateChanged(NSNotification notification)
         *      {
         *
         *      }
         *
         *      private void OnPlaybackComplete(NSNotification notification) { }
         *
         *      private void OnExitFullscreen(NSNotification notification) { }
         *
         *      private void OnEnterFullscreen(NSNotification notification) { }
         *
         *      private void ToggleFullscreen()
         *      {
         *          _player.ScalingMode = MPMovieScalingMode.None;
         *          switch (UIDevice.CurrentDevice.Orientation)
         *          {
         *              case UIDeviceOrientation.Portrait:
         *                  _player?.SetFullscreen(false, true);
         *                  break;
         *              case UIDeviceOrientation.PortraitUpsideDown:
         *                  _player?.SetFullscreen(false, true);
         *                  break;
         *              case UIDeviceOrientation.LandscapeLeft:
         *                  _player?.SetFullscreen(true, true);
         *                  break;
         *              case UIDeviceOrientation.LandscapeRight:
         *                  _player?.SetFullscreen(true, true);
         *                  break;
         *          }
         *          _player.View.SetNeedsLayout();
         *          _player.View.SetNeedsDisplay();
         *      }
         *
         *      protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
         *      {
         *          base.OnElementPropertyChanged(sender, e);
         *          if (e.PropertyName == CustomVideoSlider.FileUrlProperty.PropertyName) updateVideoPath();
         *         // if (e.PropertyName == CustomVideoSlider.FullscreenProperty.PropertyName) updateFullscreen();
         *      }
         *
         *      public override void MovedToSuperview()
         *      {
         *          base.MovedToSuperview();
         *      }
         *
         *      private void updateVideoPath()
         *      {
         *          if (_player == null) return;
         *         // _player.ControlStyle = MPMovieControlStyle.Embedded;
         *          _player.ShouldAutoplay = true;
         *          _player.ContentUrl = !string.IsNullOrWhiteSpace(this.Element.FileUrl) ? NSUrl.FromString(this.Element.FileUrl) : null;
         *          _player.PrepareToPlay();
         *      }
         *
         *      private void updateFullscreen()
         *      {
         *          if (_player == null) return;
         *          _player.SetFullscreen(true, true);
         *          _player.View.SetNeedsLayout();
         *          _player.View.SetNeedsDisplay();
         *      }
         *
         *      protected override void Dispose(bool disposing)
         *      {
         *          if (this._player != null)
         *          {
         *              this._player.Dispose();
         *              this._player = null;
         *          }
         *          base.Dispose(disposing);
         *      }
         *
         */
        protected override void OnElementChanged(ElementChangedEventArgs <CustomVideoPlayer> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                //seekBar = new UISlider();
                //SetNativeControl(seekBar);
                mainView = new UIView()
                {
                    TranslatesAutoresizingMaskIntoConstraints = false,
                };
                SetNativeControl(mainView);
            }

            if (e.OldElement != null)
            {
                videoPlayerAV.RemoveObserver(this, (NSString)"videoBounds");
                bootomToolbarView.RemoveObserver(this, (NSString)"bounds");
                UIApplication.SharedApplication.SetStatusBarHidden(false, true);
                StopPlayingAction(false);
                playerItem.RemoveObserver(this, (NSString)"loadedTimeRanges");
                playerItem.Dispose();
                player.Dispose();

                Console.WriteLine("Video Finished 1");
                //playerItem = null;
                //player = null;
            }

            if (e.NewElement != null)
            {
                slider = e.NewElement;

                _fitSize = Control.Bounds.Size;
                // except if your not running iOS 7... then it fails...
                if (_fitSize.Width <= 0 || _fitSize.Height <= 0)
                {
                    _fitSize = new SizeF(22, 22); // Per the glorious documentation known as the SDK docs
                }
                slider.CommandImageFileName = "audioPlay.png";
                slider.CommandText          = "Play";
                slider.StopPlayingAction    = StopPlayingAction;

                //seekBar = new UISlider();
                //seekBar.MaximumTrackTintColor = Color.LightGray.ToUIColor();
                //seekBar.MinimumTrackTintColor = Color.White.ToUIColor();
                //seekBar.ThumbTintColor = Color.FromHex("#827DCE").ToUIColor();
                //seekBar.Continuous = false;



                // Control.ScaleY = 5;

                if (slider.FileUrl != null)
                {
                    // playerItem = AVPlayerItem.FromUrl(NSUrl.FromString("https://s3.amazonaws.com/kargopolov/kukushka.mp3"));// (asset);
                    playerItem = AVPlayerItem.FromUrl(NSUrl.FromString(slider.FileUrl));// (asset);
                    //playerItem = AVPlayerItem.FromUrl(NSUrl.FromString("https://mindcorners.blob.core.windows.net/post-attachment-videos/6412cb27-414a-435b-a480-66af5e935cb8.mov?sv=2017-04-17&sr=b&sig=gd3mn1Gai7QZHoSpx%2Fi8x%2FHfnOutACOV7WvsVblywk0%3D&se=2017-10-11T15%3A05%3A15Z&sp=r"));
                    playerItem.AddObserver(this, (NSString)"loadedTimeRanges", NSKeyValueObservingOptions.New, IntPtr.Zero);

                    player = new AVPlayer(playerItem);


                    //player.AddObserver(this, "loadedTimeRanges", NSKeyValueObservingOptions.New, null);
                    //playerLayer = AVPlayerLayer.FromPlayer(player);
                    videoPlayerAV = new AVPlayerViewController();
                    videoPlayerAV.View.BackgroundColor  = UIColor.Clear;
                    videoPlayerAV.ShowsPlaybackControls = false;


                    videoPlayerAV.AddObserver(this, (NSString)"videoBounds", NSKeyValueObservingOptions.New, IntPtr.Zero);
                    videoPlayerAV.View.Frame = Control.Frame;
                    videoPlayerAV.Player     = player;

                    UITapGestureRecognizer tapGesture = new UITapGestureRecognizer(OnVideoTap);
                    videoView = new UIView()
                    {
                        BackgroundColor = UIColor.Clear
                    };
                    // videoView.Bounds = new CGRect(0,0,100,100);
                    videoView.AddGestureRecognizer(tapGesture);
                    //videoPlayerAV.View.AddSubview(videoView);


                    //button.CenterYAnchor.ConstraintEqualTo(videoPlayerAV.ContentOverlayView.CenterYAnchor).Active = true;
                    //button.WidthAnchor.ConstraintEqualTo(50).Active = true;
                    //button.HeightAnchor.ConstraintEqualTo(50).Active = true;



                    //videoPlayerAV.VideoGravity = AVLayerVideoGravity.ResizeAspect;

                    mainView.AddSubview(videoPlayerAV.View);
                    mainView.AddSubview(videoView);

                    videoView.TopAnchor.ConstraintEqualTo(mainView.TopAnchor).Active       = true;
                    videoView.BottomAnchor.ConstraintEqualTo(mainView.BottomAnchor).Active = true;
                    videoView.LeftAnchor.ConstraintEqualTo(mainView.LeftAnchor).Active     = true;
                    videoView.RightAnchor.ConstraintEqualTo(mainView.RightAnchor).Active   = true;
                    videoView.WidthAnchor.ConstraintEqualTo(mainView.WidthAnchor).Active   = true;
                    videoView.HeightAnchor.ConstraintEqualTo(mainView.HeightAnchor).Active = true;


                    button = new UIButton()
                    {
                        BackgroundColor = UIColor.Clear, TitleLabel = { Text = slider.CommandText }, TranslatesAutoresizingMaskIntoConstraints = false,
                    };
                    button.TouchUpInside += Button_TouchUpInside;

                    videoView.AddSubview(button);
                    button.CenterXAnchor.ConstraintEqualTo(videoView.CenterXAnchor).Active = true;
                    button.CenterYAnchor.ConstraintEqualTo(videoView.CenterYAnchor).Active = true;
                    //button.CenterXAnchor.ConstraintEqualTo(videoPlayerAV.View.CenterXAnchor).Active = true;
                    //button.CenterYAnchor.ConstraintEqualTo(videoPlayerAV.View.CenterYAnchor).Active = true;
                    button.WidthAnchor.ConstraintEqualTo(50).Active  = true;
                    button.HeightAnchor.ConstraintEqualTo(50).Active = true;



                    var center = NSNotificationCenter.DefaultCenter;
                    NSNotificationCenter.DefaultCenter.AddObserver((NSString)"UIDeviceOrientationDidChangeNotification", DeviceRotated);



                    //mainView.Layer.AddSublayer(playerLayer);
                    if (slider.AutoPlay)
                    {
                        UpdatePlaying();
                    }
                    else
                    {
                        {
                            slider.CommandImageFileName = "audioPlay.png";
                            slider.CommandText          = "Play";

                            button.Hidden = false;
                            //button.SetTitle("paused", UIControlState.Normal);
                            player.Pause();
                            isPlaying = false;
                        }

                        button.SetImage(UIImage.FromFile(slider.CommandImageFileName), UIControlState.Normal);
                    }
                }



                bootomToolbarView = new UIView()
                {
                    TranslatesAutoresizingMaskIntoConstraints = false,
                };

                bootomToolbarView.AddObserver(this, (NSString)"bounds", NSKeyValueObservingOptions.New, IntPtr.Zero);

                gradientLayer = new CAGradientLayer();
                //gradientLayer.Frame = Bounds;
                gradientLayer.Colors    = new CGColor[] { UIColor.Clear.CGColor, UIColor.Black.CGColor };
                gradientLayer.Locations = new NSNumber[2] {
                    new NSNumber(0.7), new NSNumber(1.2)
                };
                bootomToolbarView.Layer.AddSublayer(gradientLayer);
                mainView.InsertSubviewAbove(bootomToolbarView, videoPlayerAV.View);

                labelTimeLeft = new UILabel()
                {
                    TranslatesAutoresizingMaskIntoConstraints = false,
                    Text      = string.Format("{0:mm\\:ss}", TimeSpan.FromMilliseconds(slider.FileDuration ?? 0)),
                    TextColor = UIColor.White
                };
                bootomToolbarView.AddSubview(labelTimeLeft);

                labelTimePlayed = new UILabel()
                {
                    TranslatesAutoresizingMaskIntoConstraints = false,
                    Text      = "00:00",
                    TextColor = UIColor.White
                };

                bootomToolbarView.AddSubview(labelTimePlayed);

                seekBar = new UISlider()
                {
                    TranslatesAutoresizingMaskIntoConstraints = false,
                    MaximumTrackTintColor = Color.LightGray.ToUIColor(),
                    MinimumTrackTintColor = Color.White.ToUIColor(),
                    ThumbTintColor        = Color.FromHex("#827DCE").ToUIColor()
                };

                seekBar.SetThumbImage(UIImage.FromFile("audioTint.png"), UIControlState.Normal);

                seekBar.TouchDown     += Control_TouchDown;
                seekBar.TouchUpInside += Control_TouchUpInside;

                bootomToolbarView.AddSubview(seekBar);

                //videoPlayerAV.View.RightAnchor.ConstraintEqualTo(RightAnchor).Active = true;
                //videoPlayerAV.View.LeftAnchor.ConstraintEqualTo(LeftAnchor).Active = true;
                //videoPlayerAV.View.BottomAnchor.ConstraintEqualTo(BottomAnchor).Active = true;
                //videoPlayerAV.View.TopAnchor.ConstraintEqualTo(TopAnchor).Active = true;


                bootomToolbarView.RightAnchor.ConstraintEqualTo(RightAnchor).Active   = true;
                bootomToolbarView.LeftAnchor.ConstraintEqualTo(LeftAnchor).Active     = true;
                bootomToolbarView.BottomAnchor.ConstraintEqualTo(BottomAnchor).Active = true;
                bootomToolbarView.HeightAnchor.ConstraintEqualTo(40).Active           = true;


                labelTimeLeft.RightAnchor.ConstraintEqualTo(bootomToolbarView.RightAnchor, -10).Active   = true;
                labelTimeLeft.BottomAnchor.ConstraintEqualTo(bootomToolbarView.BottomAnchor, -10).Active = true;
                labelTimeLeft.WidthAnchor.ConstraintEqualTo(50).Active  = true;
                labelTimeLeft.HeightAnchor.ConstraintEqualTo(20).Active = true;

                labelTimePlayed.LeftAnchor.ConstraintEqualTo(bootomToolbarView.LeftAnchor, 10).Active      = true;
                labelTimePlayed.BottomAnchor.ConstraintEqualTo(bootomToolbarView.BottomAnchor, -10).Active = true;
                labelTimePlayed.WidthAnchor.ConstraintEqualTo(50).Active  = true;
                labelTimePlayed.HeightAnchor.ConstraintEqualTo(20).Active = true;

                seekBar.LeftAnchor.ConstraintEqualTo(labelTimePlayed.RightAnchor, 10).Active       = true;
                seekBar.RightAnchor.ConstraintEqualTo(labelTimeLeft.LeftAnchor, -10).Active        = true;
                seekBar.BottomAnchor.ConstraintEqualTo(bootomToolbarView.BottomAnchor, -10).Active = true;
                seekBar.HeightAnchor.ConstraintEqualTo(20).Active = true;



                mainView.RightAnchor.ConstraintEqualTo(RightAnchor).Active = true;
                mainView.LeftAnchor.ConstraintEqualTo(LeftAnchor).Active   = true;
                // mainView.BottomAnchor.ConstraintEqualTo(BottomAnchor).Active = true;
                mainView.TopAnchor.ConstraintEqualTo(TopAnchor).Active = true;

                // bootomToolbarView = new UIView();
                // //bootomToolbarView.BackgroundColor =  UIColor.Orange;
                // CAGradientLayer gradientLayer = new CAGradientLayer();
                // gradientLayer.Frame = bootomToolbarView.Frame;
                // gradientLayer.Colors = new CGColor[] {UIColor.Clear.CGColor, UIColor.Orange.CGColor};
                // bootomToolbarView.Layer.AddSublayer(gradientLayer);
                // //bootomToolbarView.BackgroundColor = new CGGradient(CGColorSpace.CreateAcesCGLinear(), new CGColor[] {UIColor.Clear.CGColor, UIColor.Black.CGColor });
                // labelTimePlayed = new UILabel();
                //// labelTimePlayed.Frame = new CGRect(0,10,50,20);
                // labelTimePlayed.Text = "00:00";
                // labelTimePlayed.TextColor = UIColor.White;

                // //seekBar.Frame = new CGRect(50, 10, 100, 20);

                // labelTimeLeft = new UILabel();
                // //labelTimeLeft.Frame = new CGRect(150, 10, 50, 20);
                // labelTimeLeft.Text = "00:00";
                // labelTimeLeft.Text = string.Format("{0:mm\\:ss}", TimeSpan.FromMilliseconds(slider.FileDuration ?? 0));
                // labelTimeLeft.TextColor = UIColor.White;


                // //bootomToolbarView.Frame = new CGRect(0, 10, 200, 20);
                // bootomToolbarView.AddSubview(labelTimePlayed);
                // bootomToolbarView.InsertSubviewAbove(labelTimeLeft, labelTimePlayed);
                // bootomToolbarView.InsertSubviewAbove(seekBar, labelTimeLeft);
                // mainView.InsertSubviewAbove(bootomToolbarView, videoPlayerAV.View);



                //playerLayer = AVPlayerLayer.FromPlayer(player);
                UIApplication.SharedApplication.SetStatusBarHidden(true, true);
            }

            //seekBar.TouchDown += Control_TouchDown;
            //seekBar.TouchUpInside += Control_TouchUpInside;
        }