public static AVPlayerItem GetPlayerItem(this IMediaItem mediaItem)
        {
            AVAsset asset;

            if (mediaItem.MediaLocation == MediaLocation.Embedded)
            {
                string directory = Path.GetDirectoryName(mediaItem.MediaUri);
                string filename  = Path.GetFileNameWithoutExtension(mediaItem.MediaUri);
                string extension = Path.GetExtension(mediaItem.MediaUri).Substring(1);
                NSUrl  url       = NSBundle.MainBundle.GetUrlForResource(filename, extension, directory);
                asset = AVAsset.FromUrl(url);
            }
            else if (RequestHeaders != null && RequestHeaders.Any())
            {
                asset = AVUrlAsset.Create(NSUrl.FromString(mediaItem.MediaUri), GetOptionsWithHeaders(RequestHeaders));
            }
            else
            {
                asset = AVAsset.FromUrl(NSUrl.FromString(mediaItem.MediaUri));
            }

            var playerItem = AVPlayerItem.FromAsset(asset);

            return(playerItem);
        }
        public async Task SetQueue(IList <Song> songs)
        {
            System.Diagnostics.Debug.WriteLine("SetQeueue()");
            await Task.Run(() =>
            {
                if (songs == null)
                {
                    songs = new ObservableCollection <Song>();
                }

                if (!Enumerable.SequenceEqual(_queue, songs, _comparer))
                {
                    _queue = songs;
                    _getQueue?.Invoke(_queue);
                }

                _pos = 0;
                _getQueuePos(_pos);
                try
                {
                    NSUrl url = new NSUrl(_queue[_pos].Uri);
                    NSMutableDictionary dict = new NSMutableDictionary();
                    dict.Add(new NSString("AVURLAssetPreferPreciseDurationAndTimingKey"), new NSNumber(true));
                    var playerItem = AVPlayerItem.FromAsset(AVUrlAsset.Create(url, new AVUrlAssetOptions(dict)));

                    _player.ReplaceCurrentItemWithPlayerItem(playerItem);
                    Pause();
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e);
                }
            });
        }
        public void Start(int pos)
        {
            System.Diagnostics.Debug.WriteLine("Start()");

            // workaround to fix song auto-playing when app launches
            if (isFirst)
            {
                isFirst = false;
                return;
            }

            if (pos >= 0 && pos < _queue.Count)
            {
                _pos = pos;
                _getQueuePos(_pos);
                try
                {
                    NSUrl url = new NSUrl(_queue[_pos].Uri);
                    NSMutableDictionary dict = new NSMutableDictionary();
                    dict.Add(new NSString("AVURLAssetPreferPreciseDurationAndTimingKey"), new NSNumber(true));
                    var playerItem = AVPlayerItem.FromAsset(AVUrlAsset.Create(url, new AVUrlAssetOptions(dict)));
                    _player.ReplaceCurrentItemWithPlayerItem(playerItem);
                    NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, OnCompletion);
                    UpdateInfoCenter();
                    Play();
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e);
                }
            }
        }
Exemple #4
0
        private void Play(Uri uri)
        {
            var nsAsset       = AVAsset.FromUrl(DecodeUri(uri));
            var streamingItem = AVPlayerItem.FromAsset(nsAsset);

            _player.ReplaceCurrentItemWithPlayerItem(streamingItem);
        }
Exemple #5
0
        public static VideoHandle Create(string uri, Action loaded, Action <string> error)
        {
            var handle = new VideoHandle();
            var url    = new NSUrl(uri);

            handle.Asset = new AVUrlAsset(url, (AVUrlAssetOptions)null);
            handle.Asset.LoadValuesAsynchronously(new string[] { "tracks" },
                                                  () => DispatchQueue.MainQueue.DispatchAsync(
                                                      () => {
                NSError e;
                var status = handle.Asset.StatusOfValue("tracks", out e);
                if (status == AVKeyValueStatus.Loaded)
                {
                    handle.Output = new AVPlayerItemVideoOutput(
                        new CVPixelBufferAttributes
                    {
                        PixelFormatType = CVPixelFormatType.CV32BGRA,
                    });

                    handle.PlayerItem = AVPlayerItem.FromAsset(handle.Asset);
                    handle.PlayerItem.AddOutput(handle.Output);
                    handle.Player = AVPlayer.FromPlayerItem(handle.PlayerItem);
                    PollReadyState(handle, loaded, error);
                }
                else
                {
                    error("Failed to load: " + status.ToString());
                }
            }));

            return(handle);
        }
Exemple #6
0
        protected virtual void InitializeSource()
        {
            PlaybackSession.NaturalDuration    = TimeSpan.Zero;
            PlaybackSession.PositionFromPlayer = TimeSpan.Zero;

            // Reset player
            TryDisposePlayer();

            if (Source == null)
            {
                return;
            }

            try
            {
                InitializePlayer();

                PlaybackSession.PlaybackState = MediaPlaybackState.Opening;

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

                if (Source is MediaPlaybackList)
                {
                    var items = ((MediaPlaybackList)Source).Items;
                    foreach (var item in items)
                    {
                        var asset = AVAsset.FromUrl(DecodeUri(item.Source.Uri));
                        _player.InsertItem(new AVPlayerItem(asset), null);
                    }
                }
                else
                {
                    var nsAsset       = AVAsset.FromUrl(DecodeUri(((MediaSource)Source).Uri));
                    var streamingItem = AVPlayerItem.FromAsset(nsAsset);

                    _player.ReplaceCurrentItemWithPlayerItem(streamingItem);
                }

                _player.CurrentItem.AddObserver(_observer, new NSString("duration"), NSKeyValueObservingOptions.Initial, _player.Handle);
                _player.CurrentItem.AddObserver(_observer, new NSString("status"), NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, _player.Handle);
                _player.CurrentItem.AddObserver(_observer, 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;

                MediaOpened?.Invoke(this, null);
            }
            catch (Exception ex)
            {
                OnMediaFailed(ex);
            }
        }
Exemple #7
0
        public void FromAssert_Null()
        {
            // Apple's AVCustomEdit samples calls this with `nil`
            Assert.Null(AVPlayerItem.FromAsset(null), "1");

            if (TestRuntime.CheckSystemAndSDKVersion(7, 0))
            {
                Assert.Null(AVPlayerItem.FromAsset(null, null), "2");
            }
        }
        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");
            }
        }
        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;
        }
Exemple #10
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);
            }
        }
        private AVPlayerItem GetPlayerItem(NSUrl url)
        {
            AVAsset asset;

            if (RequestHeaders != null && RequestHeaders.Any())
            {
                var options = GetOptionsWithHeaders(RequestHeaders);

                asset = AVUrlAsset.Create(url, options);
            }
            else
            {
                asset = AVAsset.FromUrl(url);
            }

            var playerItem = AVPlayerItem.FromAsset(asset);

            return(playerItem);
        }
 public void QueueFile(string fileName)
 {
     if (string.IsNullOrWhiteSpace(fileName))
     {
         return;
     }
     using (var url = NSUrl.FromString(fileName))
     {
         var asset = AVAsset.FromUrl(url);
         var playerItem = AVPlayerItem.FromAsset(asset);
         if (Player == null)
         {
             Player = AVPlayer.FromPlayerItem(playerItem);
             if (Player == null)
             {
                 return;
             }
             else
             {
                 NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, OnPlayerDidFinishPlaying, NSObject.FromObject(playerItem));
             }
         }
     }
 }
Exemple #13
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            NSUrl        movieUrl = NSUrl.FromString("http://devstreaming.apple.com/videos/wwdc/2016/504m956dgg4hlw2uez9/504/504_sd_whats_new_in_http_live_streaming.mp4?dl=1");
            AVUrlAsset   asset    = AVUrlAsset.Create(movieUrl);
            AVPlayerItem item     = AVPlayerItem.FromAsset(asset);

            AVPlayer player = AVPlayer.FromPlayerItem(item);
            AVPlayerViewController controller = new AVPlayerViewController();

            controller.Player = player;

            AddChildViewController(controller);
            View.AddSubview(controller.View);
            controller.View.Frame = View.Frame;

            controller.ShowSubtitles(
                NSUrl.FromString("https://raw.githubusercontent.com/eplt/WWDC-Video-Subtitles/master/2016/SD/English/504_sd_whats_new_in_http_live_streaming_eng.srt")
                );

            player.Play();
        }
        public async Task Play(Func <Task> ifNotAvailable)
        {
            if (Status == PlayerStatus.PAUSED)
            {
                Status = PlayerStatus.PLAYING;
                //We are simply paused so just start again
                player.Play();
                return;
            }

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

                Cover = null;

                AVAsset      nsAsset       = AVUrlAsset.FromUrl(nsUrl);
                AVPlayerItem streamingItem = AVPlayerItem.FromAsset(nsAsset);

                nsAsset.LoadValuesAsynchronously(new string[] { "commonMetadata" }, delegate
                {
                    foreach (AVMetadataItem item in streamingItem.Asset.CommonMetadata)
                    {
                        if (item.KeySpace == AVMetadata.KeySpaceID3 && item.CommonKey == AVMetadata.CommonKeyArtwork)
                        {
                            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                            {
                                Cover = UIImage.LoadFromData(item.Value as NSData);
                            }
                            else
                            {
                                NSObject data;
                                (item.Value as NSMutableDictionary).TryGetValue(new NSString("data"), out data);
                                Cover = UIImage.LoadFromData(data as NSData);
                            }
                        }
                    }

                    if (Cover == null)
                    {
                        Cover = UIImage.FromFile("placeholder_cover.png");
                    }
                });

                if (player.CurrentItem != null)
                {
                    // Remove the observer before destructing the current item
                    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, async(notification) =>
                {
                    await PlayNext();
                }, player.CurrentItem);

                player.Play();
            }
            catch (Exception ex)
            {
                Status = PlayerStatus.STOPPED;

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