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); }
public void PlayPrepare(string fileName) { try { var filePath = _Storage.GetPath(fileName); var url = NSUrl.FromFilename(filePath); if (_Player == null) { _Player = new AVPlayer(); } if (_PlayerItem != null) { _Player.RemoveTimeObserver(_TimeChanged); // for skipping 1-2 extra triggering for new item creation code below CleanPlayerItem(); } PlayerReady = false; _Asset = AVAsset.FromUrl(url); _PlayerItem = new AVPlayerItem(_Asset); _PlayerItem.AddObserver(this, _status, NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, _Player.Handle); _PlayerItem.AddObserver(this, _error, NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, _Player.Handle); _Player.ReplaceCurrentItemWithPlayerItem(_PlayerItem); _Player.Rate = 1; _Player.Pause(); // HACK: stop autoplaying after recording _TimeChanged = _Player.AddPeriodicTimeObserver(new CMTime(1, 1), DispatchQueue.MainQueue, time => { // skip restart event if (_isRestart) { _isRestart = false; return; } if (_PlayerItem != null && _PlayerItem.Duration != CMTime.Indefinite) { var stopped = time == _PlayerItem.Duration; PlaybackStatus?.Invoke(this, new PlaybackEventArgs { CurrentTime = time.Seconds, Duration = _PlayerItem.Duration.Seconds, Stopped = stopped }); if (stopped) { _isRestart = true; _Player.Seek(CMTime.Zero); } } }); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("*** AudioService.PlayPrepare - Exception: {0}", ex)); } }
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); }
void synchronizePlayerWithEditor() { if (Player == null) { return; } AVPlayerItem playerItem = Editor.PlayerItem; var status = (NSString)"status"; if (PlayerItem != playerItem) { if (PlayerItem != null) { PlayerItem.RemoveObserver(this, status); NSNotificationCenter.DefaultCenter.RemoveObserver(observer, AVPlayerItem.DidPlayToEndTimeNotification, PlayerItem); } PlayerItem = playerItem; if (PlayerItem != null) { PlayerItem.SeekingWaitsForVideoCompositionRendering = true; 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); } }
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") { string filePath = ResolveMsAppDataUri(Element.Source); if (string.IsNullOrEmpty(filePath)) { throw new ArgumentException("Invalid Uri", "Source"); } asset = AVAsset.FromUrl(NSUrl.FromFilename(filePath)); } else { asset = AVUrlAsset.Create(NSUrl.FromString(Element.Source.AbsoluteUri), GetOptionsWithHeaders(Element.HttpHeaders)); } AVPlayerItem item = new AVPlayerItem(asset); RemoveStatusObserver(); _statusObserver = (NSObject)item.AddObserver("status", NSKeyValueObservingOptions.New, ObserveStatus); if (Control.Player != null) { Control.Player.ReplaceCurrentItemWithPlayerItem(item); Control.Player.Volume = (float)Element.Volume; } else { Control.Player = new AVPlayer(item); _rateObserver = (NSObject)Control.Player.AddObserver("rate", NSKeyValueObservingOptions.New, ObserveRate); Control.Player.Volume = (float)Element.Volume; } if (Element.AutoPlay) { Play(); } } else { if (Element.CurrentState == MediaElementState.Playing || Element.CurrentState == MediaElementState.Buffering) { Control.Player.Pause(); Controller.CurrentState = MediaElementState.Stopped; } } }
public override void ViewDidLoad() { base.ViewDidLoad(); _asset = AVAsset.FromUrl(NSUrl.FromFilename("SampleVideo.mp4")); _playerItem = new AVPlayerItem(_asset); _playerItem.SeekingWaitsForVideoCompositionRendering = true; _playerItem.AddObserver(this, (NSString)"status", NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, StatusObservationContext.Handle); NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, (notification) => { Console.WriteLine("Seek Zero = true"); seekToZeroBeforePlaying = true; this.updatePlayPauseButton(); }, _playerItem); _player = new AVPlayer(_playerItem); _playerLayer = AVPlayerLayer.FromPlayer(_player); _playerLayer.Frame = this.playerView.Frame; this.playerView.Layer.AddSublayer(_playerLayer); updateScrubber(); updateTimeLabel(); slider.EditingDidBegin += slider_EditingDidBegin; slider.EditingDidEnd += slider_EditingDidEnd; slider.ValueChanged += slider_ValueChanged; playpauseButton.TouchUpInside += playpauseButton_TouchUpInside; playing = true; _player.Play(); }
// 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); } }
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); }
private void UpdateSource() { if (Element.Source != null) { AVAsset asset = null; if (Element.Source.Scheme == null) { // file path asset = AVAsset.FromUrl(NSUrl.FromFilename(Element.Source.OriginalString)); } else 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; } } }
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); }
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(); }); }
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(); }
void UpdateSource() { if (Element.Source != null) { AVAsset asset = null; var uriSource = Element.Source as UriMediaSource; if (uriSource != null) { if (uriSource.Uri.Scheme == "ms-appx") { if (uriSource.Uri.LocalPath.Length <= 1) { return; } // used for a file embedded in the application package asset = AVAsset.FromUrl(NSUrl.FromFilename(uriSource.Uri.LocalPath.Substring(1))); } else if (uriSource.Uri.Scheme == "ms-appdata") { string filePath = Platform.ResolveMsAppDataUri(uriSource.Uri); if (string.IsNullOrEmpty(filePath)) { throw new ArgumentException("Invalid Uri", "Source"); } asset = AVAsset.FromUrl(NSUrl.FromFilename(filePath)); } else { asset = AVUrlAsset.Create(NSUrl.FromString(uriSource.Uri.AbsoluteUri)); } } else { var fileSource = Element.Source as FileMediaSource; if (fileSource != null) { asset = AVAsset.FromUrl(NSUrl.FromFilename(fileSource.File)); } } var item = new AVPlayerItem(asset); RemoveStatusObserver(); _statusObserver = (NSObject)item.AddObserver("status", NSKeyValueObservingOptions.New, ObserveStatus); if (_avPlayerViewController.Player != null) { _avPlayerViewController.Player.ReplaceCurrentItemWithPlayerItem(item); } else { _avPlayerViewController.Player = new AVPlayer(item); _rateObserver = (NSObject)_avPlayerViewController.Player.AddObserver("rate", NSKeyValueObservingOptions.New, ObserveRate); } if (Element.AutoPlay) { Play(); } } else { if (Element.CurrentState == MediaElementState.Playing || Element.CurrentState == MediaElementState.Buffering) { _avPlayerViewController.Player.Pause(); Controller.CurrentState = MediaElementState.Stopped; } } }
void synchronizePlayerWithEditor() { if (Player == null) return; AVPlayerItem playerItem = Editor.PlayerItem; var status = (NSString)"status"; if (PlayerItem != playerItem) { if (PlayerItem != null) { PlayerItem.RemoveObserver (this, status); NSNotificationCenter.DefaultCenter.RemoveObserver (observer, AVPlayerItem.DidPlayToEndTimeNotification, PlayerItem); } PlayerItem = playerItem; if (PlayerItem != null) { PlayerItem.SeekingWaitsForVideoCompositionRendering = true; 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); } }
private void UpdateSource() { System.Diagnostics.Debug.WriteLine("UpdateSource"); if (Element.Source != null) { AVAsset asset = null; if (Element.Source.Scheme == null) { // file path asset = AVAsset.FromUrl(NSUrl.FromFilename(Element.Source.OriginalString)); } else 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") { string filePath = string.Empty; if (Element.Source.LocalPath.StartsWith("/local")) { filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Element.Source.LocalPath.Substring(7)); } else if (Element.Source.LocalPath.StartsWith("/temp")) { filePath = Path.Combine(Path.GetTempPath(), Element.Source.LocalPath.Substring(6)); } asset = AVAsset.FromUrl(NSUrl.FromFilename(filePath)); } else { asset = AVUrlAsset.Create(NSUrl.FromString(Element.Source.AbsoluteUri), GetOptionsWithHeaders(Element.HttpHeaders)); } AVPlayerItem item = new AVPlayerItem(asset); RemoveStatusObserver(); _observer = (NSObject)item.AddObserver("status", NSKeyValueObservingOptions.New, ObserveStatus); if (_avPlayerViewController.Player != null) { _avPlayerViewController.Player.ReplaceCurrentItemWithPlayerItem(item); } else { _avPlayerViewController.Player = new AVPlayer(item); } if (Element.AutoPlay) { var audioSession = AVAudioSession.SharedInstance(); NSError err = audioSession.SetCategory(AVAudioSession.CategoryPlayback); audioSession.SetMode(AVAudioSession.ModeMoviePlayback, out err); err = audioSession.SetActive(true); _avPlayerViewController.Player.Play(); Element.CurrentState = MediaElementState.Playing; } } else { if (Element.CurrentState == MediaElementState.Playing || Element.CurrentState == MediaElementState.Buffering) { Element.Stop(); } } }
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); } }
void SetSource() { 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)); NSUrl url = null; try { string absUri = new Uri(uri).AbsoluteUri; url = new NSUrl(absUri); } catch (Exception ex) { Debug.WriteLine(ex.Message); } if (url != null) { asset = AVAsset.FromUrl(url); } } } 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) { //ExploreProperties(asset); playerItem = new AVPlayerItem(asset); } else { playerItem = null; } player.ReplaceCurrentItemWithPlayerItem(playerItem); if (playerItem != null) { //playbackBufferEmptyObserver = (NSObject)playerItem.AddObserver("playbackBufferEmpty", // NSKeyValueObservingOptions.New, // AVPlayerItem_BufferUpdated); playbackLikelyToKeepUpObserver = (NSObject)playerItem.AddObserver("playbackLikelyToKeepUp", NSKeyValueObservingOptions.New, AVPlayerItem_BufferUpdated); //playbackBufferFullObserver = (NSObject)playerItem.AddObserver("playbackBufferFull", // NSKeyValueObservingOptions.New, // AVPlayerItem_BufferUpdated); if (Element.AutoPlay) { player.Play(); } } }
void SetSource() { AVAsset asset = null; if (Element.Source is UriVideoSource) { string uri = (Element.Source as UriVideoSource).Uri; if (uri.Contains("Bearer=")) { string[] stringSeparators = new string[] { "Bearer=" }; string[] split; split = uri.Split(stringSeparators, StringSplitOptions.None); if (split != null && split.Length == 2) { string bearer = "Bearer " + split[1]; if (!String.IsNullOrWhiteSpace(split[0])) { NSMutableDictionary nativeHeaders = new NSMutableDictionary(); nativeHeaders.Add(new NSString("Authorization"), (NSString)bearer); var nativeHeadersKey = (NSString)"AVURLAssetHTTPHeaderFieldsKey"; var options = new AVUrlAssetOptions(NSDictionary.FromObjectAndKey( nativeHeaders, nativeHeadersKey )); asset = new AVUrlAsset(new NSUrl(uri), options); } } } else if (!String.IsNullOrWhiteSpace(uri)) { //asset = AVAsset.FromUrl(new NSUrl(uri)); NSUrl url = null; try { string absUri = new Uri(uri).AbsoluteUri; url = new NSUrl(absUri); } catch (Exception ex) { Debug.WriteLine(ex.Message); } if (url != null) { asset = AVAsset.FromUrl(url); } } } 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) { //ExploreProperties(asset); playerItem = new AVPlayerItem(asset); } else { playerItem = null; } player.ReplaceCurrentItemWithPlayerItem(playerItem); if (playerItem != null) { //playbackBufferEmptyObserver = (NSObject)playerItem.AddObserver("playbackBufferEmpty", // NSKeyValueObservingOptions.New, // AVPlayerItem_BufferUpdated); playbackLikelyToKeepUpObserver = (NSObject)playerItem.AddObserver("playbackLikelyToKeepUp", NSKeyValueObservingOptions.New, AVPlayerItem_BufferUpdated); //playbackBufferFullObserver = (NSObject)playerItem.AddObserver("playbackBufferFull", // NSKeyValueObservingOptions.New, // AVPlayerItem_BufferUpdated); if (Element.AutoPlay) { player.Play(); } } }
/* * 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; }