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();
			};
		}
        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);
        }
Ejemplo n.º 3
0
        public void FromAssert_Null()
        {
            TestRuntime.AssertXcodeVersion(5, 1);
            // Apple's AVCustomEdit samples calls this with `nil`
            Assert.Null(AVPlayerItem.FromAsset(null), "1");

            if (TestRuntime.CheckXcodeVersion(5, 0, 1))
            {
                Assert.Null(AVPlayerItem.FromAsset(null, null), "2");
            }
        }
Ejemplo n.º 4
0
        void SetSource()
        {
            _logger.Log("SetSource invoked.");

            AVAsset asset = null;

            if (Element.Source is UriVideoSource)
            {
                string uri = (Element.Source as UriVideoSource).Uri;

                if (!String.IsNullOrWhiteSpace(uri))
                {
                    asset = AVAsset.FromUrl(new NSUrl(uri));
                }
            }
            else if (Element.Source is FileVideoSource)
            {
                string uri = (Element.Source as FileVideoSource).File;

                if (!String.IsNullOrWhiteSpace(uri))
                {
                    asset = AVAsset.FromUrl(new NSUrl(uri));
                }
            }
            else if (Element.Source is ResourceVideoSource)
            {
                string path = (Element.Source as ResourceVideoSource).Path;

                if (!String.IsNullOrWhiteSpace(path))
                {
                    string directory = Path.GetDirectoryName(path);
                    string filename  = Path.GetFileNameWithoutExtension(path);
                    string extension = Path.GetExtension(path).Substring(1);
                    NSUrl  url       = NSBundle.MainBundle.GetUrlForResource(filename, extension, directory);
                    asset = AVAsset.FromUrl(url);
                }
            }

            if (asset != null)
            {
                playerItem = new AVPlayerItem(asset);
            }
            else
            {
                playerItem = null;
            }

            player.ReplaceCurrentItemWithPlayerItem(playerItem);

            if (playerItem != null && Element.AutoPlay)
            {
                player.Play();
            }
        }
Ejemplo n.º 5
0
        private VideoPlayerEventArgs CreateVideoPlayerEventArgs()
        {
            AVPlayerItem currentItem = this._playerControl.Player.CurrentItem;

            if (currentItem != null)
            {
                double num = !double.IsNaN(currentItem.Duration.Seconds) ? currentItem.Duration.Seconds : 0.0;
                return(new VideoPlayerEventArgs(TimeSpan.FromSeconds(!double.IsNaN(currentItem.CurrentTime.Seconds) ? currentItem.CurrentTime.Seconds : 0.0), TimeSpan.FromSeconds(num), this._playerControl.Player.Rate));
            }
            return(null);
        }
        public async Task Play(IMediaFile mediaFile = null)
        {
            if (mediaFile != null)
            {
                nsUrl = new NSUrl(mediaFile.Url);
            }

            if (Status == MediaPlayerStatus.Paused)
            {
                Status = MediaPlayerStatus.Playing;
                //We are simply paused so just start again
                Player.Play();
                return;
            }

            try
            {
                // Start off with the status LOADING.
                Status = MediaPlayerStatus.Buffering;

                var options = MediaFileUrlHelper.GetOptionsWithHeaders(RequestHeaders);

                var nsAsset       = AVUrlAsset.Create(nsUrl, options);
                var streamingItem = AVPlayerItem.FromAsset(nsAsset);

                Player.CurrentItem?.RemoveObserver(this, new NSString("status"));

                Player.ReplaceCurrentItemWithPlayerItem(streamingItem);
                streamingItem.AddObserver(this, new NSString("status"), NSKeyValueObservingOptions.New, Player.Handle);
                streamingItem.AddObserver(this, new NSString("loadedTimeRanges"),
                                          NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, Player.Handle);

                Player.CurrentItem.SeekingWaitsForVideoCompositionRendering = true;
                Player.CurrentItem.AddObserver(this, (NSString)"status", NSKeyValueObservingOptions.New |
                                               NSKeyValueObservingOptions.Initial,
                                               StatusObservationContext.Handle);

                NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification,
                                                               notification => MediaFinished?.Invoke(this, new MediaFinishedEventArgs(mediaFile)), Player.CurrentItem);

                Player.Play();
            }
            catch (Exception ex)
            {
                OnMediaFailed();
                Status = MediaPlayerStatus.Stopped;

                //unable to start playback log error
                Console.WriteLine("Unable to start playback: " + ex);
            }

            await Task.CompletedTask;
        }
        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));
                };
            }
        }
Ejemplo n.º 8
0
		public override async void WindowControllerDidLoadNib (NSWindowController windowController)
		{
			base.WindowControllerDidLoadNib (windowController);
			
			// Add code to here after the controller has loaded the document window

			var filename = Path.Combine (NSBundle.MainBundle.BundlePath, "sample_iTunes.mov");

			NSUrl url = NSUrl.FromFilename ("/Users/kichang/Downloads/sample_iTunes.mov");
			asset = AVAsset.FromUrl (url);


			string[] keys = { "playable", "hasProtectedContent", "tracks", "duration" };

			Task task = asset.LoadValuesTaskAsync (keys);

			await task;

			NSError assetError;
			if (asset.StatusOfValue ("playable", out assetError) == AVKeyValueStatus.Failed) {
				return;
			}

			if (asset.Playable) {
				float height = asset.Tracks [0].NaturalSize.Height;
				float width = asset.Tracks [0].NaturalSize.Width;

				playerItem = new AVPlayerItem (asset);
				player = new AVPlayer ();
				playerLayer = AVPlayerLayer.FromPlayer (player);


				playerView.WantsLayer = true;
				playerView.Layer.BackgroundColor = new CGColor (1, 1, 1, 1);


				playerLayer.Frame = new RectangleF (0, 0, width, height);
				playerView.Frame = playerLayer.Frame;


				playerView.Layer.AddSublayer (playerLayer);


				player.ReplaceCurrentItemWithPlayerItem (playerItem);


				player.Play ();

			} 



		}
		void ReleasePlayerItem()
		{
			if (_playerItem != null) {
				_playerItem.CancelPendingSeeks ();
				_playerItem.RemoveObserver (this, (NSString)"status");
				_playerItem.RemoveObserver (this, (NSString)"playbackBufferFull");
				_playerItem.RemoveObserver (this, (NSString)"playbackBufferEmpty");
				_playerItem.RemoveObserver (this, (NSString)"playbackLikelyToKeepUp");

				_playerItem = null;
			}
		}
Ejemplo n.º 10
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.º 11
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.º 12
0
        private void Play(int index)
        {
            Stop();
            Prepare();
            var songToPlay = _items.ElementAt(index);

            UpdateNowPlaying(songToPlay);
            var avasset      = AVAsset.FromUrl(NSUrl.FromString(songToPlay.SongUri.OriginalString));
            var avplayerItem = new AVPlayerItem(avasset);

            _avPlayer = new AVPlayer(avplayerItem);
            _avPlayer.Play();
        }
Ejemplo n.º 13
0
        void InitializePlayer()
        {
            ShouldDisposeView = true;

            if (DownloadedFile != null)
            {
                PlayerItem = new AVPlayerItem(DownloadedFile);
            }
            else if (Path.IsUrl())
            {
                PlayerItem = new AVPlayerItem(new NSUrl(Path));
            }
            else
            {
                PlayerItem = new AVPlayerItem(AVAsset.FromUrl(NSUrl.FromString("file://" + IO.File(Path).FullName)));
            }

            Player = new AVPlayer(PlayerItem)
            {
                Volume = 1.0f
            };

            DidPlayToEndTimeObservation = AVPlayerItem.Notifications.ObserveDidPlayToEndTime(PlayerItem, (_, _) =>
            {
                Thread.UI.Post(() => Dispose());
            });

            StatusObservation = PlayerItem.AddObserver(nameof(AVPlayerItem.Status), 0, _ =>
            {
                if (PlayerItem?.Status == AVPlayerItemStatus.ReadyToPlay)
                {
                    try { Audio.ConfigureAudio(AVAudioSessionCategory.Playback); }
                    catch { }

                    Player?.Play();
                    return;
                }

                if (PlayerItem?.Status == AVPlayerItemStatus.Failed)
                {
                    Log.For(this).Error($"Failed to play {Path}");
                }
                else
                {
                    Log.For(this).Error($"An error occured during playing {Path}");
                }

                RetryToDownloadTrack();
            });
        }
Ejemplo n.º 14
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'");
                        }
        }
Ejemplo n.º 15
0
        public static double CurrentTimeSeconds(this AVPlayer player, AVPlayerItem item)
        {
            if (player?.CurrentItem != item)
            {
                return(0);
            }
            if (player?.CurrentTime == null)
            {
                return(0);
            }
            var seconds = player.CurrentTime.IsInvalid ? 0 : player.CurrentTime.Seconds;

            return(double.IsNaN(seconds) ? 0 : seconds);
        }
Ejemplo n.º 16
0
        private void PlatformDispose(bool disposing)
        {
            if (Player != null)
            {
                Player.Dispose();
                Player = null;
            }

            if (movie != null)
            {
                movie.Dispose();
                movie = null;
            }
        }
Ejemplo n.º 17
0
        private void PlatformDispose(bool disposing)
        {
            if (_sound == null)
                return;
                
            playToEndObserver.Dispose ();
            playToEndObserver = null;

            _sound.Dispose();
            _sound = null;

            _player.Dispose();
            _player = null;
        }
Ejemplo n.º 18
0
        protected virtual void InitializeSource()
        {
            PlaybackSession.NaturalDuration    = TimeSpan.Zero;
            PlaybackSession.PositionFromPlayer = TimeSpan.Zero;

            if (Source == null)
            {
                return;
            }

            try
            {
                // Reset player
                TryDisposePlayer();
                InitializePlayer();

                PlaybackSession.PlaybackState = MediaPlaybackState.Opening;

                var nsAsset       = AVAsset.FromUrl(DecodeUri(((MediaSource)Source).Uri));
                var streamingItem = AVPlayerItem.FromAsset(nsAsset);

                _player.CurrentItem?.RemoveObserver(this, new NSString("duration"), _player.Handle);
                _player.CurrentItem?.RemoveObserver(this, new NSString("status"), _player.Handle);
                _player.CurrentItem?.RemoveObserver(this, new NSString("loadedTimeRanges"), _player.Handle);

                _player.ReplaceCurrentItemWithPlayerItem(streamingItem);

                _player.CurrentItem.AddObserver(this, new NSString("duration"), NSKeyValueObservingOptions.Initial, _player.Handle);
                _player.CurrentItem.AddObserver(this, new NSString("status"), NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, _player.Handle);
                _player.CurrentItem.AddObserver(this, new NSString("loadedTimeRanges"), NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, _player.Handle);

                _player.CurrentItem.SeekingWaitsForVideoCompositionRendering = true;

                // Adapt pitch to prevent "metallic echo" when changing playback rate
                _player.CurrentItem.AudioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.TimeDomain;

                // Disable subtitles if any
                var mediaSelectionGroup = _player.CurrentItem.Asset.MediaSelectionGroupForMediaCharacteristic(AVMediaCharacteristic.Legible);
                if (mediaSelectionGroup != null)
                {
                    _player.CurrentItem.SelectMediaOption(null, mediaSelectionGroup);
                }

                MediaOpened?.Invoke(this, null);
            }
            catch (Exception ex)
            {
                OnMediaFailed(ex);
            }
        }
Ejemplo n.º 19
0
        private void UpdateSource()
        {
            if (Element.Source != null)
            {
                AVAsset asset = null;
                if (Element.Source.Scheme == "ms-appx")
                {
                    // used for a file embedded in the application package
                    asset = AVAsset.FromUrl(NSUrl.FromFilename(Element.Source.LocalPath.Substring(1)));
                }
                else if (Element.Source.Scheme == "ms-appdata")
                {
                    asset = AVAsset.FromUrl(NSUrl.FromFilename(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Element.Source.LocalPath.Substring(1))));
                }
                else
                {
                    asset = AVUrlAsset.Create(NSUrl.FromString(Element.Source.ToString()), GetOptionsWithHeaders(Element.HttpHeaders));
                }

                AVPlayerItem item = new AVPlayerItem(asset);

                if (observer != null)
                {
                    if (_avPlayerViewController.Player != null && _avPlayerViewController.Player.CurrentItem != null)
                    {
                        _avPlayerViewController.Player.CurrentItem.RemoveObserver(observer, "status");
                    }

                    observer.Dispose();
                    observer = null;
                }

                observer = (NSObject)item.AddObserver("status", 0, ObserveStatus);

                if (_avPlayerViewController.Player != null)
                {
                    _avPlayerViewController.Player.ReplaceCurrentItemWithPlayerItem(item);
                }
                else
                {
                    _avPlayerViewController.Player = new AVPlayer(item);
                }

                if (Element.AutoPlay)
                {
                    _avPlayerViewController.Player.Play();
                    Element.CurrentState = MediaElementState.Playing;
                }
            }
        }
Ejemplo n.º 20
0
        private void SetSource()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Element.Source))
                {
                    return;
                }
                _prepared = false;
                if (_player != null)
                {
                    _player.Dispose();
                    _player = null;
                }

                AVPlayerItem playerItem = null;
                if (Element.Source.StartsWith("http://") || Element.Source.StartsWith("https://"))
                {
                    playerItem = new AVPlayerItem(AVAsset.FromUrl(NSUrl.FromString(Element.Source)));
                }
                else
                {
                    playerItem = new AVPlayerItem(NSUrl.FromFilename(Element.Source));
                }

                NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, DidVideoFinishPlaying, playerItem);
                NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.ItemFailedToPlayToEndTimeNotification, DidVideoErrorOcurred, playerItem);
                NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.NewErrorLogEntryNotification, DidVideoErrorOcurred, playerItem);
                //NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.PlaybackStalledNotification, DidVideoPrepared, playerItem);

                _player = new AVPlayer(playerItem);
                _player.ActionAtItemEnd  = AVPlayerActionAtItemEnd.None;
                _playerController.Player = _player;
                _prepared = true;

                if (Element.AutoPlay)
                {
                    _player.Play();
                }

                if (_player.Error != null)
                {
                    Element.OnError(_playerController?.Player?.Error?.LocalizedDescription);
                }
            }
            catch (Exception e)
            {
                Element.OnError(e.Message);
            }
        }
Ejemplo n.º 21
0
        private void Play()
        {
            if (string.IsNullOrEmpty(MediaUrl))
            {
                LoadingSpinner.Hidden = true;
                return;
            }

            //f4v is not supported on iOS (thanks Apple)
            if (MediaUrl.EndsWith(".f4v", StringComparison.CurrentCultureIgnoreCase))
            {
                //Show alert
                LoadingSpinner.Hidden = true;
                _dialog.Show(Translation.alert_display_failed_title,
                             Translation.alert_display_failed_body,
                             Translation.general_close,
                             async() => { await ViewModel?.CloseCommand?.ExecuteAsync(); });
                return;
            }

            if (MediaUrl.EndsWith(".mp4", StringComparison.CurrentCultureIgnoreCase) ||
                MediaUrl.EndsWith(".m4v", StringComparison.CurrentCultureIgnoreCase))
            {
                ImageView.Hidden = true;

                NSUrl        url  = NSUrl.CreateFileUrl(MediaUrl, null);
                AVPlayerItem item = new AVPlayerItem(url);

                _avLooper = new AVPlayerLooper(_avplayer, item, CoreMedia.CMTimeRange.InvalidRange);
                _avplayer.ReplaceCurrentItemWithPlayerItem(item);
                _avplayer.Play();
            }
            else if (MediaUrl.EndsWith(".png", StringComparison.CurrentCultureIgnoreCase))
            {
                _avplayer.Dispose();
                _avplayer = null;

                _avplayerController.RemoveFromParentViewController();
                _avplayerController.View.RemoveFromSuperview();
                _avplayerController.Dispose();
                _avplayerController = null;

                UIImage image = UIImage.FromFile(MediaUrl);
                ImageView.Image = image;
            }


            LoadingSpinner.Hidden = true;
        }
Ejemplo n.º 22
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();
        }
Ejemplo n.º 23
0
        private void DisposeChildren()
        {
            player?.Pause();

            playerController?.RemoveFromParentViewController();
            playerController?.Dispose();
            playerController = null;

            player?.Dispose();
            playerItem?.Dispose();

            player = null;

            playerItem = null;
        }
 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 ();
 }
Ejemplo n.º 25
0
        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();
        }
Ejemplo n.º 26
0
        void SetupPlayback()
        {
            var movieURL = NSBundle.MainBundle.GetUrlForResource("samplemovie", "mov");
            var asset    = new AVUrlAsset(movieURL, (AVUrlAssetOptions)null);

            // Create a new `AVPlayerItem` and make it our player's current item.
            //
            // Using `AVAsset` now runs the risk of blocking the current thread (the
            // main UI thread) whilst I/O happens to populate the properties. It's prudent
            // to defer our work until the properties we need have been loaded.
            //
            // These properties can be passed in at initialization to `AVPlayerItem`,
            // which are then loaded automatically by `AVPlayer`.
            PlayerItem = new AVPlayerItem(asset, assetKeysRequiredToPlay);
        }
Ejemplo n.º 27
0
 void PlayerFinished(AVPlayerItem item)
 {
     if (CurrentItem == item)
     {
         SecondaryPlayer.Play();
     }
     if (player1.CurrentItem == item)
     {
         ResetPlayer1();
     }
     else if (player2.CurrentItem == item)
     {
         ResetPlayer2();
     }
 }
Ejemplo n.º 28
0
        public void LoadAsync(string source)
        {
            AVAsset asset;

            if (string.IsNullOrWhiteSpace(source))
            {
                return;
            }
            _prepared = false;
            if (audioPlayer != null)
            {
                audioPlayer.Dispose();
                audioPlayer = null;
            }
            _prepared = false;
            _timer    = new System.Timers.Timer(1000)
            {
                AutoReset = true
            };

            if (source.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase) ||
                source.StartsWith("https://", StringComparison.CurrentCultureIgnoreCase))
            {
                asset = AVAsset.FromUrl(NSUrl.FromString(source));
            }
            else
            {
                asset = AVAsset.FromUrl(NSUrl.FromFilename(source));
            }

            var playerItem = new AVPlayerItem(asset);

            audioPlayer = new AVPlayer(playerItem);

            NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, DidVideoFinishPlaying, playerItem);
            //NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.ItemFailedToPlayToEndTimeNotification, DidVideoErrorOcurred, playerItem);
            //NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.NewErrorLogEntryNotification, DidVideoErrorOcurred, playerItem);

            _timer.Elapsed += (s, e) =>
            {
                if (SeekPositionChanged != null)
                {
                    SeekPositionChanged.Invoke(this, CurrentPosition);
                }
            };
            _prepared = true;
            SetTotalDuration();
        }
Ejemplo n.º 29
0
        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;
        }
Ejemplo n.º 30
0
        public void LoadFromAsset(AVAsset asset)
        {
            _asset = asset;

            if (_item != null)
            {
                _playbackEndedObserver.Dispose();
                _item.Dispose();
            }

            _item = new AVPlayerItem(asset);
            _playbackEndedObserver = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, HandlePlaybackCompleted, _item);

            Player.Pause();
            Player.ReplaceCurrentItemWithPlayerItem(_item);
        }
Ejemplo n.º 31
0
        private void PlatformDispose(bool disposing)
        {
            if (_sound == null)
            {
                return;
            }

            playToEndObserver.Dispose();
            playToEndObserver = null;

            _sound.Dispose();
            _sound = null;

            _player.Dispose();
            _player = null;
        }
Ejemplo n.º 32
0
        protected override void OnElementChanged(ElementChangedEventArgs <myVideoPlayer> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                if (Control == null)
                {
                    // Create AVPlayerViewController
                    _playerViewController = new AVPlayerViewController();

                    // Set Player property to AVPlayer
                    player = new AVPlayer();
                    _playerViewController.Player = player;

                    // Use the View from the controller as the native control
                    SetNativeControl(_playerViewController.View);

                    asset = AVAsset.FromUrl(new NSUrl("https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
                    if (asset != null)
                    {
                        string[] keys = { "playable", "hasProtectedContent" };

                        asset.LoadValuesAsynchronously(keys, () =>
                        {
                            DispatchQueue.MainQueue.DispatchAsync(() =>
                            {
                                // Device.BeginInvokeOnMainThread(() => {
                                if (asset == null)
                                {
                                    return;
                                }

                                Console.WriteLine(asset.StatusOfValue("playable", out err));

                                playerItem = new AVPlayerItem(asset);
                                player.ReplaceCurrentItemWithPlayerItem(playerItem);
                                if (playerItem != null)
                                {
                                    player.Play();
                                }
                            });
                        });
                    }
                }
            }
        }
Ejemplo n.º 33
0
        public void PrepareForUrl(NSUrl url)
        {
            AssetUrl = url;

            CleanPreviousResources();
            PlayerItem = new AVPlayerItem(url);

            PlayerItem.AddObserver(this, StatusKey, NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, StatusContext.Handle);
            PlayerItem.AddObserver(this, LoadedTimeRangesKey, NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, TimeRangesContext.Handle);
            PlayerItem.AddObserver(this, PlaybackBufferEmptyKey, NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, PlaybackBufferEmptyContext.Handle);

            if (Player != null)
            {
                Player.Dispose();
            }
            Player = new AVPlayer(PlayerItem);
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 35
0
        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);
        }
Ejemplo n.º 36
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();
        }
Ejemplo n.º 38
0
        private void CreateNativePlayer()
        {
            var source = this.Element.Source;

            if (string.IsNullOrWhiteSpace(source))
            {
                return;
            }

            var asset = AVAsset.FromUrl(new NSUrl(source));
            var item  = new AVPlayerItem(asset);
            var playerViewController = new AVPlayerViewController();

            _player = new AVPlayer(item);
            playerViewController.Player = _player;
            this.SetNativeControl(playerViewController.View);
        }
		void SetupPlayback()
		{
			var movieURL = NSBundle.MainBundle.GetUrlForResource ("samplemovie", "mov");
			var asset = new AVUrlAsset (movieURL, (AVUrlAssetOptions)null);

			// Create a new `AVPlayerItem` and make it our player's current item.
			//
			// Using `AVAsset` now runs the risk of blocking the current thread (the
			// main UI thread) whilst I/O happens to populate the properties. It's prudent
			// to defer our work until the properties we need have been loaded.
			//
			// These properties can be passed in at initialization to `AVPlayerItem`,
			// which are then loaded automatically by `AVPlayer`.
			PlayerItem = new AVPlayerItem (asset, assetKeysRequiredToPlay);
		}
		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;
					});
				});
			}
		}
        public void Play(Uri source)
        {
            Debug.WriteLine("Start playing");
            AVAsset asset = AVAsset.FromUrl(source);
            AVPlayerItem playerItem = new AVPlayerItem(asset);
            avPlayer = new AVPlayer(playerItem);

            //            playerItem.AddObserver(observer: this,
            //                keyPath: new NSString("playbackLikelyToKeepUp"),
            //                options: NSKeyValueObservingOptions.New,
            //                context: itemContext);
            //            playerItem.AddObserver(observer: this,
            //                keyPath: new NSString("status"),
            //                options: NSKeyValueObservingOptions.New,
            //                context: itemContext);
            //            avPlayer.AddObserver(observer: this,
            //                keyPath: new NSString("status"),
            //                options: NSKeyValueObservingOptions.New,
            //                context: playerContext);

            avPlayer.Play();
        }
		void synchronizePlayerWithEditor()
		{
			if (Player == null)
				return;

			AVPlayerItem playerItem = Editor.PlayerItem;
			var status = (NSString)"status";

			if (this.PlayerItem != playerItem) {
				if (PlayerItem != null) {
					PlayerItem.RemoveObserver (this, status);
					NSNotificationCenter.DefaultCenter.RemoveObserver (observer, AVPlayerItem.DidPlayToEndTimeNotification, PlayerItem);
				}

				PlayerItem = playerItem;

				if (PlayerItem != null) {
					this.PlayerItem.SeekingWaitsForVideoCompositionRendering = true;
					this.PlayerItem.AddObserver (this, status, NSKeyValueObservingOptions.New|
						NSKeyValueObservingOptions.Initial, StatusObservationContext.Handle);
					observer = NSNotificationCenter.DefaultCenter.AddObserver (AVPlayerItem.DidPlayToEndTimeNotification, (notification) => {
						Console.WriteLine("Seek Zero = true");
						seekToZeroBeforePlaying = true;
					}, playerItem);
					//NSNotificationCenter.DefaultCenter.AddObserver (this, new MonoTouch.ObjCRuntime.Selector ("playerItemEnded:"), AVPlayerItem.DidPlayToEndTimeNotification, playerItem);
				}

				Player.ReplaceCurrentItemWithPlayerItem (playerItem);
			}
		}
        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;
 }
		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 ();
						}
				}));
			}
		}
Ejemplo n.º 46
0
 private void PlatformInitialize(NSUrl url)
 {
     _sound = AVPlayerItem.FromUrl(url);
     _player = AVPlayer.FromPlayerItem(_sound);
     playToEndObserver = AVPlayerItem.Notifications.ObserveDidPlayToEndTime(OnFinishedPlaying);
 }