Exemplo n.º 1
0
        private void InitializePlayer()
        {
            _player                  = new AVQueuePlayer();
            _videoLayer              = AVPlayerLayer.FromPlayer(_player);
            _videoLayer.Frame        = ((VideoSurface)RenderSurface).Frame;
            _videoLayer.VideoGravity = AVLayerVideoGravity.ResizeAspect;
            ((VideoSurface)RenderSurface).Layer.AddSublayer(_videoLayer);

            var avSession = AVAudioSession.SharedInstance();

            avSession.SetCategory(AVAudioSessionCategory.Playback);

            NSError activationError = null;

            avSession.SetActive(true, out activationError);
            if (activationError != null)
            {
                this.Log().WarnIfEnabled(() => $"Could not activate audio session: {activationError.LocalizedDescription}");
            }

            _videoLayer.AddObserver(this, new NSString("videoRect"), NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, _videoLayer.Handle);
            _player.AddObserver(this, new NSString("rate"), NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, RateObservationContext.Handle);

            _itemFailedToPlayToEndTimeNotification = AVPlayerItem.Notifications.ObserveItemFailedToPlayToEndTime((sender, args) => OnMediaFailed(new Exception(args.Error.LocalizedDescription)));
            _playbackStalledNotification           = AVPlayerItem.Notifications.ObservePlaybackStalled((sender, args) => OnMediaFailed());
            _didPlayToEndTimeNotification          = AVPlayerItem.Notifications.ObserveDidPlayToEndTime((sender, args) => OnMediaEnded(sender, args));

            _periodicTimeObserverObject = _player.AddPeriodicTimeObserver(new CMTime(1, 4), DispatchQueue.MainQueue, delegate
            {
                if (_player?.CurrentItem == null)
                {
                    return;
                }

                if (PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
                {
                    PlaybackSession.PositionFromPlayer = Position;
                }
            });
        }