예제 #1
0
        public async Task Play(IMediaFile mediaFile = null)
        {
            var sameMediaFile = mediaFile == null || mediaFile.Equals(_currentMediaFile);

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

            if (mediaFile != null)
            {
                nsUrl             = MediaFileUrlHelper.GetUrlFor(mediaFile);
                _currentMediaFile = mediaFile;
            }

            try
            {
                InitializePlayer();

                Status = MediaPlayerStatus.Buffering;

                var playerItem = GetPlayerItem(nsUrl);

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

                Player.ReplaceCurrentItemWithPlayerItem(playerItem);
                CurrentItem.AddObserver(this, new NSString("loadedTimeRanges"),
                                        NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New,
                                        LoadedTimeRangesObservationContext.Handle);

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


                NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification,
                                                               notification => MediaFinished?.Invoke(this, new MediaFinishedEventArgs(mediaFile)), 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;
        }