protected virtual void PlayInternal(bool resume) { try { if (!RunningOnExtender || !Config.Instance.EnableTranscode360 || Helper.IsExtenderNativeVideo(this.Filename)) { PlayAndGoFullScreen(this.Filename); } else { // if we are on an extender, we need to start up our transcoder try { PlayFileWithTranscode(this.Filename); } catch { // in case t360 is not installed - we may get an assembly loading failure PlayAndGoFullScreen(this.Filename); } } if (resume) { PlaybackController.Seek(PlayState.PositionTicks); } } catch (Exception ex) { Logger.ReportException("Failed to play " + this.Filename, ex); } }
/// <summary> /// Method that is called immediately after the view item is displayed. /// </summary> public override void Init() { _playbackWpfUserControl = new PlaybackWpfUserControl(); canvasPlaybackControl.Children.Add(_playbackWpfUserControl); _audioPlayerControl = ClientControl.Instance.GenerateAudioPlayerControl(WindowInformation); _audioPlayerControl.Dock = DockStyle.Fill; _audioPlayerControlHost.Child = _audioPlayerControl; _imageViewerControl = new ImageViewerWpfControl(WindowInformation); _imageViewerControl.VerticalAlignment = System.Windows.VerticalAlignment.Stretch; _imageViewerControl.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; _imageViewerControl.EnableMouseControlledPtz = true; _imageViewerControl.Selected = true; canvasVideo.Children.Add(_imageViewerControl); _playbackFQID = ClientControl.Instance.GeneratePlaybackController(); _playbackWpfUserControl.Init(_playbackFQID); _imageViewerControl.PlaybackControllerFQID = _playbackFQID; _audioPlayerControl.PlaybackControllerFQID = _playbackFQID; PlaybackController pc = ClientControl.Instance.GetPlaybackController(_playbackFQID); pc.SkipGaps = false; SetUpApplicationEventListeners(); _imageViewerControl.Initialize(); // Make sure Click events have been configured if (_viewItemManager.SelectedCamera != null) { ViewItemManagerPropertyChangedEvent(this, null); } }
public AudioPlayerViewModel() { mediaPlayer = CrossMediaManager.Current; MediaPlayer.StatusChanged += (sender, e) => { RaisePropertyChanged(() => Status); RaisePropertyChanged(() => Position); }; MediaPlayer.PlayingChanged += (sender, e) => { RaisePropertyChanged(() => Position); }; MediaPlayer.MediaQueue.QueueMediaChanged += (q_sender, q_e) => { RaisePropertyChanged(() => PlayingText); if (CurrentTrack != null) { CurrentTrack.MetadataUpdated += (m_sender, m_e) => { RaisePropertyChanged(() => PlayingText); }; } }; PlayPauseCommand = new MvxAsyncCommand(async() => await PlaybackController.PlayPause()); SkipPreviousCommand = new MvxAsyncCommand(async() => await PlaybackController.PlayPreviousOrSeekToStart()); SkipNextCommand = new MvxAsyncCommand(async() => await PlaybackController.PlayNext()); }
public void SetUp() { // testScheduler = new TestScheduler(); // origSched = RxApp.DeferredScheduler; // RxApp.DeferredScheduler = testScheduler; lockObject = new ManualResetEvent(false); requestExecutor = new RequestExecutorStub(); audioPlayerStub = new AudioPlayerStub(); playbackController = new PlaybackController(audioPlayerStub, requestExecutor); authenticator = new Authenticator(requestExecutor, new SettingsStub()); mediaLibraryBrowser = new MediaLibraryBrowser(requestExecutor); requestExecutor.Responses.Add(new LoginResponse() { LoggedIn = false, CurrentUserElement = new CurrentUserElement() { Login = "******", Slug = "userSlug" } }); loginFormViewModel = new LoginFormViewModel(authenticator); mediaBrowserViewModel = new MediaBrowserViewModel(mediaLibraryBrowser, new SettingsStub(), loginFormViewModel, new MixViewModelFactory(playbackController, mediaLibraryBrowser, loginFormViewModel.UserLoggedInObservable)); }
static void Main(string[] args) { var controller = new PlaybackController(); controller.MediaOpening += (s, e) => { $"EVT: {nameof(controller.MediaOpening)}".Info(typeof(Program)); }; controller.MediaOpened += (s, e) => { $"EVT: {nameof(controller.MediaOpened)}".Info(typeof(Program)); }; controller.BufferingStarted += (s, e) => { $"EVT: {nameof(controller.BufferingStarted)}".Info(typeof(Program)); }; controller.BufferingEnded += (s, e) => { $"EVT: {nameof(controller.BufferingEnded)}".Info(typeof(Program)); }; controller.MediaBlockAvailable += (s, e) => { $"EVT: {nameof(controller.MediaBlockAvailable)} | {e.Block.MediaType,8} | {e.Position.TotalSeconds,6:0.00}".Trace(typeof(Program)); }; controller.MediaEnded += (s, e) => { $"EVT: {nameof(controller.MediaEnded)} | POS: {controller.Position.TotalSeconds,8:0.00}".Info(typeof(Program)); }; var hasSeeked = false; controller.PropertyChanged += (s, e) => { if (hasSeeked == false && controller.Position.TotalSeconds >= 3) { hasSeeked = true; controller.Position = TimeSpan.FromSeconds(40); controller.SpeedRatio = 3.0d; } }; controller.Open(TestInputs.MatroskaLocalFile); controller.Play(); Terminal.ReadKey(true, true); }
private void PlayAndGoFullScreen(string file) { this.fileToPlay = file; Play(file); PlaybackController.GoToFullScreen(); MarkWatched(); PlaybackController.OnProgress += new EventHandler <PlaybackStateEventArgs>(PlaybackController_OnProgress); }
public async void TogglePlay(object sender, EventArgs arg) { if (MediaPlayer.State == MediaPlayerState.Playing) { await PlaybackController.Pause(); } else { await PlaybackController.Play(); } }
public async void StopAsync() { try { await PlaybackController.Stop(); } catch (Exception) { // Commented } }
public override void SwitchedToLocalPlayback(NSObject lastKnownStreamPosition, NSObject error) { //base.SwitchedToLocalPlayback(lastKnownStreamPosition, error); var x = (NSNumber)lastKnownStreamPosition; if (x.Int32Value > 0) { PlaybackController.Play(); } Debug.WriteLine("Switched to Local Playback"); }
private void PlayAndGoFullScreen(string file) { this.fileToPlay = file; this.currentTitle = file.Replace('\\', '/').ToLower(); this.alternateTitle = Path.GetFileNameWithoutExtension(file).ToLower(); Play(file); if (!QueueItem) { PlaybackController.GoToFullScreen(); } PlaybackController.OnProgress += new EventHandler <PlaybackStateEventArgs>(PlaybackController_OnProgress); }
public async Task SeekTo_NegativePosition_SeeksToZero() { SetupSeek(TimeSpan.Zero); Duration = TimeSpan.Zero; var playbackController = new PlaybackController(MediaManager); await playbackController.SeekTo(-1f); _mediaManagerMock .Verify(mediaManager => mediaManager.Seek(TimeSpan.Zero), Times.Once); }
public static PlayableItem GetCurrentPlaybackItemUsingMetadataTitle(PlaybackController controllerInstance, IEnumerable <PlayableItem> playableItems, string metadataTitle, out int filePlaylistPosition, out int currentMediaIndex) { filePlaylistPosition = -1; currentMediaIndex = -1; metadataTitle = metadataTitle.ToLower(); // Loop through each PlayableItem and try to find a match foreach (PlayableItem playable in playableItems) { if (playable.HasMediaItems) { // The PlayableItem has Media items, so loop through each one and look for a match int totalFileCount = 0; int numMediaItems = playable.MediaItems.Count(); for (int i = 0; i < numMediaItems; i++) { Media media = playable.MediaItems.ElementAt(i); IEnumerable <string> files = controllerInstance.GetPlayableFiles(media); int index = PlaybackControllerHelper.GetIndexOfFileInPlaylist(files, metadataTitle); if (index != -1) { filePlaylistPosition = index + totalFileCount; currentMediaIndex = i; return(playable); } totalFileCount += files.Count(); } } else { // There are no Media items so just find the index using the Files property int index = PlaybackControllerHelper.GetIndexOfFileInPlaylist(playable.FilesFormattedForPlayer, metadataTitle); if (index != -1) { filePlaylistPosition = index; return(playable); } } } return(null); }
public async Task SeekTo_PositionGreaterThanDuration_SeeksToEnd() { var duration = TimeSpan.FromSeconds(5); SetupSeek(duration); Duration = duration; var playbackController = new PlaybackController(MediaManager); await playbackController.SeekTo(10); _mediaManagerMock .Verify(mediaManager => mediaManager.Seek(duration)); }
public async Task PlayPause_Playing_Pauses() { _mediaManagerMock .Setup(mediaManager => mediaManager.Pause()) .Returns(Task.FromResult(0)); MediaManagerStatus = MediaPlayerStatus.Playing; var playbackController = new PlaybackController(MediaManager); await playbackController.PlayPause(); _mediaManagerMock .Verify(mediaManager => mediaManager.Pause(), Times.Once); }
public async Task PlayPause_NotPlaying_Pauses(MediaPlayerStatus notPlayingStatus) { _mediaManagerMock .Setup(mediaManager => mediaManager.Play((IMediaFile)null)) .Returns(Task.FromResult(0)); MediaManagerStatus = notPlayingStatus; var playbackController = new PlaybackController(MediaManager); await playbackController.PlayPause(); _mediaManagerMock .Verify(mediaManager => mediaManager.Play((IMediaFile)null), Times.Once); }
public async Task PlayPrevious_QueueHasPrevious_PlaysPrevious() { _mediaManagerMock .Setup(mediaManager => mediaManager.PlayPrevious()) .Returns(Task.FromResult(0)); MediaQueue = GetMediaQueue(hasPrevious: true); var playbackController = new PlaybackController(MediaManager); await playbackController.PlayPrevious(); _mediaManagerMock .Verify(mediaManager => mediaManager.PlayPrevious(), Times.Once); }
protected override void PlayInternal(bool resume) { if (PlaybackController.IsPlaying) { PlaybackController.Pause(); } MediaType type = MediaTypeResolver.DetermineType(path); ConfigData.ExternalPlayer p = configuredPlayers[type]; string args = string.Format(p.Args, path); Process.Start(p.Command, args); MarkWatched(); }
public virtual void Play(string file) { Logger.ReportVerbose("About to play : " + file); if (QueueItem && this.PlayableItems != null && this.PlayableItems.Count() > 0) { PlaybackController.QueueMedia(this.PlayableItems); } else if (QueueItem) { PlaybackController.QueueMedia(file); } else { PlaybackController.PlayMedia(file); } }
//private DateTime startTime; protected override void PlayInternal(bool resume) { if (PlaybackController.IsPlaying) { PlaybackController.Stop(); //stop whatever is playing } //startTime = DateTime.Now; //grab this so we can attempt to determine how long we are playing the item //MediaBrowser.Library.Logging.Logger.ReportInfo("Playing external. Duration: " + duration); MediaType type = MediaTypeResolver.DetermineType(path); ConfigData.ExternalPlayer p = configuredPlayers[type]; string args = string.Format(p.Args, path); Process player = Process.Start(p.Command, args); Async.Queue("Ext Player Mgmt", () => ManageExtPlayer(player, p.MinimizeMCE, p.ShowSplashScreen)); }
public async Task SeekTo_PositionBetweenStartAndEnd_SeeksToPosition() { var secondsToSeekTo = 5; var positionToSeekTo = TimeSpan.FromSeconds(secondsToSeekTo); SetupSeek(positionToSeekTo); Duration = TimeSpan.FromSeconds(10); var playbackController = new PlaybackController(MediaManager); await playbackController.SeekTo(secondsToSeekTo); _mediaManagerMock .Verify(mediaManager => mediaManager.Seek(positionToSeekTo), Times.Once); }
internal void Play() { if (Microsoft.MediaCenter.UI.Application.ApplicationThread != System.Threading.Thread.CurrentThread) { Application.UIDeferredInvokeIfRequired(() => Play()); return; } System.Diagnostics.Debug.Assert(Microsoft.MediaCenter.UI.Application.ApplicationThread == Thread.CurrentThread); Prepare(); if (!MediaItems.Any() && !Files.Any()) { Microsoft.MediaCenter.MediaCenterEnvironment ev = Application.MediaCenterEnvironment; ev.Dialog(Application.CurrentInstance.StringData("NoContentDial"), Application.CurrentInstance.StringData("Playstr"), Microsoft.MediaCenter.DialogButtons.Ok, 500, true); return; } if (CurrentMedia != null) { Logger.ReportInfo(string.Format("{0} about to play {1}({2}) ", PlaybackController.ControllerName, DisplayName, CurrentMedia.Files.FirstOrDefault())); } // If the controller already has active playable items, stop it and wait for it to flush out if (!QueueItem) { PlaybackController.StopAndWait(); } // Run all pre-play processes RunPrePlayProcesses(); if (!QueueItem && StopAllPlaybackBeforePlaying) { StopAllApplicationPlayback(); } if (UseAutoPlay) { Logger.ReportVerbose("Playing with autoplay. Marking watched since we have no way of getting status on this."); MarkWatchedIfNeeded(); } else { //AdjustRefreshRate(); PlaybackController.Play(this); } }
// change an image when tapping a play button private async void TapGestureRecognizer_Tapped(object sender, EventArgs e) { // editing it later isTapPlayButton = !isTapPlayButton; if (isTapPlayButton) { MyPlayButton.Source = "pausebutton.png"; await CrossMediaManager.Current.Play("http://zmp3-mp3-s1-te-zmp3-fpthn-1.zadn.vn/11779c713b35d26b8b24/992888775050630550?key=ip7LPVb1UkVmpS_F51-Fng&expires=1495601215"); CrossMediaManager.Current.PlayingChanged += Current_PlayingChanged; } else { MyPlayButton.Source = "playbutton.png"; await PlaybackController.Pause(); } }
public NowPlayingViewModel() { _playbackController = IoC.Get <PlaybackController>(); SelectionChangedCommand = new ReactiveCommand(); SelectionChangedCommand.Where(x => x != null) .Select(x => ((IEnumerable)x).Cast <TrackStateViewModel>()) .Subscribe(x => SelectedItems = x); RemoveSelectedCommand = new ReactiveCommand(); RemoveSelectedCommand.Subscribe(param => new List <TrackStateViewModel>(SelectedItems) .ForEach(x => Playlist.Remove(x))); RemoveAllCommand = new ReactiveCommand(); RemoveAllCommand.Subscribe(param => Playlist.Clear()); PlaySelectedCommand = new ReactiveCommand(); PlaySelectedCommand.Subscribe(param => _playbackController.Play(SelectedItems.First())); }
public NowPlayingViewModel() { _playbackController = IoC.Get<PlaybackController>(); SelectionChangedCommand = new ReactiveCommand(); SelectionChangedCommand.Where(x => x != null) .Select(x => ((IEnumerable) x).Cast<TrackStateViewModel>()) .Subscribe(x => SelectedItems = x); RemoveSelectedCommand = new ReactiveCommand(); RemoveSelectedCommand.Subscribe(param => new List<TrackStateViewModel>(SelectedItems) .ForEach(x => Playlist.Remove(x))); RemoveAllCommand = new ReactiveCommand(); RemoveAllCommand.Subscribe(param => Playlist.Clear()); PlaySelectedCommand = new ReactiveCommand(); PlaySelectedCommand.Subscribe(param => _playbackController.Play(SelectedItems.First())); }
private void PrepareControls(Panel videoPanel) { _currentVideoPanel = videoPanel; _videoPictureBox = new PictureBox(); videoPanel.Controls.Clear(); videoPanel.Controls.Add(_videoPictureBox); _videoPictureBox.Dock = DockStyle.Fill; _playbackFQID = null;//Null в данном случае - использование стандартного способа управления контролом _playbackUserControl = ClientControl.Instance.GeneratePlaybackUserControl(); _playbackUserControl.Visible = true; _playbackUserControl.Dock = DockStyle.Fill; _playbackController = ClientControl.Instance.GetPlaybackController(_playbackFQID); _bitmapSource = new BitmapSource(); _bitmapSource.PlaybackFQID = _playbackFQID; _bitmapSource.NewBitmapEvent += _bitmapSource_NewBitmapEvent; _bitmapSource.Selected = true; }
/// <summary> /// Then playback is based on Media items, this will populate the MediaCollection using the items /// </summary> public static void PopulateMediaCollectionUsingMediaItems(PlaybackController controllerInstance, MediaCollection coll, PlayableItem playable) { int currentFileIndex = 0; int collectionIndex = coll.Count; int numItems = playable.MediaItems.Count(); for (int mediaIndex = 0; mediaIndex < numItems; mediaIndex++) { Media media = playable.MediaItems.ElementAt(mediaIndex); IEnumerable <string> files = controllerInstance.GetPlayableFiles(media); int numFiles = files.Count(); // Create a MediaCollectionItem for each file to play for (int i = 0; i < numFiles; i++) { string path = files.ElementAt(i); Dictionary <string, object> friendlyData = new Dictionary <string, object>(); // Embed the playlist index, since we could have multiple playlists queued up // which prevents us from being able to use MediaCollection.CurrentIndex friendlyData["FilePlaylistPosition"] = currentFileIndex.ToString(); // Embed the PlayableItemId so we can identify which one to track progress for friendlyData["PlayableItemId"] = playable.Id.ToString(); // Embed the Media index so we can identify which one to track progress for friendlyData["MediaIndex"] = mediaIndex.ToString(); // Set a friendly title friendlyData["Title"] = media.Name; coll.AddItem(path, collectionIndex, -1, string.Empty, friendlyData); currentFileIndex++; collectionIndex++; } } }
/// <summary> /// Then playback is based on Media items, this will populate the MediaCollection using the items /// </summary> public static void PopulateMediaCollectionUsingMediaItems(PlaybackController controllerInstance, MediaCollection coll, PlayableItem playable) { int currentFileIndex = 0; int collectionIndex = coll.Count; int numItems = playable.MediaItems.Count(); for (int mediaIndex = 0; mediaIndex < numItems; mediaIndex++) { Media media = playable.MediaItems.ElementAt(mediaIndex); IEnumerable<string> files = controllerInstance.GetPlayableFiles(media); int numFiles = files.Count(); // Create a MediaCollectionItem for each file to play for (int i = 0; i < numFiles; i++) { string path = files.ElementAt(i); Dictionary<string, object> friendlyData = new Dictionary<string, object>(); // Embed the playlist index, since we could have multiple playlists queued up // which prevents us from being able to use MediaCollection.CurrentIndex friendlyData["FilePlaylistPosition"] = currentFileIndex.ToString(); // Embed the PlayableItemId so we can identify which one to track progress for friendlyData["PlayableItemId"] = playable.Id.ToString(); // Embed the Media index so we can identify which one to track progress for friendlyData["MediaIndex"] = mediaIndex.ToString(); // Set a friendly title friendlyData["Title"] = media.Name; coll.AddItem(path, collectionIndex, -1, string.Empty, friendlyData); currentFileIndex++; collectionIndex++; } } }
internal void Play() { Prepare(); if (!HasMediaItems && !Files.Any()) { Microsoft.MediaCenter.MediaCenterEnvironment ev = Microsoft.MediaCenter.Hosting.AddInHost.Current.MediaCenterEnvironment; ev.Dialog(Application.CurrentInstance.StringData("NoContentDial"), Application.CurrentInstance.StringData("Playstr"), Microsoft.MediaCenter.DialogButtons.Ok, 500, true); return; } Logger.ReportInfo(PlaybackController.ControllerName + " about to play " + DisplayName); // If the controller already has active playable items, stop it and wait for it to flush out if (!QueueItem) { PlaybackController.StopAndWait(); } // Run all pre-play processes RunPrePlayProcesses(); if (!QueueItem && StopAllPlaybackBeforePlaying) { StopAllApplicationPlayback(); } if (UseAutoPlay) { Logger.ReportVerbose("Playing with autoplay. Marking watched since we have no way of getting status on this."); MarkWatchedIfNeeded(); } else { PlaybackController.Play(this); } }
public void SetUp() { fileSystemBrowserStub = new FileSystemBrowserStub(); downloadingMediaContent = Features.DownloadingMediaContent; testScheduler = new TestScheduler(); origSched = RxApp.DeferredScheduler; RxApp.DeferredScheduler = testScheduler; aMix = new Mix(new MixElement(), 0); lockObject = new ManualResetEvent(false); audioPlayer = new AudioPlayerStub(); requestExecutor = new RequestExecutorStub(); playbackController = new PlaybackController(audioPlayer, requestExecutor); mediaLibraryBrowser = new MediaLibraryBrowser(requestExecutor); userLoggedInSubject = new Subject <bool>(); mixViewModel = new MixViewModel(aMix, playbackController, mediaLibraryBrowser, userLoggedInSubject); mixViewModel.FileSystemBrowser = fileSystemBrowserStub; mixViewModel.WebAccessProxy = new WebAccessProxyStub(); lockObject.Reset(); }
private async void HandleNotificationActions(object sender, string action) { if (action.Equals(MediaServiceBase.ActionPlay)) { await PlaybackController.Play(); } else if (action.Equals(MediaServiceBase.ActionPause)) { await PlaybackController.Pause(); } else if (action.Equals(MediaServiceBase.ActionPrevious)) { await PlaybackController.PlayPreviousOrSeekToStart(); } else if (action.Equals(MediaServiceBase.ActionNext)) { await PlaybackController.PlayNext(); } else if (action.Equals(MediaServiceBase.ActionStop)) { await Stop(); } }
public void BindEvents() { PlaybackController.MediaItemChanged += PlaybackController_MediaItemChanged; PlaybackController.MediaItemFinished += PlaybackController_MediaItemFinished; PlaybackController.StateChanged += PlaybackController_StateChanged; MediaPlayer.MediaPlayer.BeforePlaying += MediaPlayer_BeforePlaying; element.Stop = () => PlaybackController.Stop(); element.Play = () => PlaybackController.Play(); element.Abort = () => aborted = true; element.Reset = () => aborted = false; element.PlayQueueItem = PlayQueueItem; element.GetCurrentMedia = () => MediaPlayer.MediaQueue.Current != null ? new Realm.Of.Y.Manager.Models.Container.MediaItem(MediaPlayer.MediaQueue.Current.MediaUri) { Title = MediaPlayer.MediaQueue.Current.Title } : null; seeker.ProgressChanged += Seeker_ProgressChanged; youtube_button_prev.Click += (sender, e) => { PlaybackController.PlayPrevious(); element?.OnPrev?.Invoke(); }; youtube_button_next.Click += (sender, e) => { PlaybackController.PlayNext(); element?.OnNext?.Invoke(); }; fullscreen_button.Click += (s, e) => { Fullscreen_button_Click(null, null); }; btnPlay.Click += TogglePlay; element.OnPlayVideo = (items) => PlayVideo(items); element.SetFullScrean = (n) => { fullScrean = !n; Fullscreen_button_Click(null, null); }; }
private void OnLoad(object sender, EventArgs e) { // In this sample we create a specific PlaybackController. // All commands to this controller needs to be sent via messages with the destination as _playbackFQID. // All message Indications coming from this controller will have sender as _playbackController. _playbackFQID = null; // use default playbackController instead of: ClientControl.Instance.GeneratePlaybackController(); _playbackUserControl = ClientControl.Instance.GeneratePlaybackUserControl(); _playbackUserControl.Visible = true; _playbackUserControl.Dock = DockStyle.Fill; panelPlayback.Controls.Add(_playbackUserControl); _playbackUserControl.BringToFront(); _playbackUserControl.Init(_playbackFQID); _playbackController = ClientControl.Instance.GetPlaybackController(_playbackFQID); _bitmapSource = new BitmapSource(); _bitmapSource.PlaybackFQID = _playbackFQID; _bitmapSource.NewBitmapEvent += _bitmapSource_NewBitmapEvent; _bitmapSource.Selected = true; EnvironmentManager.Instance.TraceFunctionCalls = true; }
/// <summary> /// Then playback is based on Media items, this will populate the MediaCollection using the items /// </summary> public static void PopulateMediaCollectionUsingMediaItems(PlaybackController controllerInstance, MediaCollection coll, PlayableItem playable) { int currentFileIndex = 0; int collectionIndex = coll.Count; int numItems = playable.MediaItems.Count(); for (int mediaIndex = 0; mediaIndex < numItems; mediaIndex++) { Media media = playable.MediaItems.ElementAt(mediaIndex); IEnumerable<string> files = controllerInstance.GetPlayableFiles(media); int numFiles = files.Count(); // Create a MediaCollectionItem for each file to play for (int i = 0; i < numFiles; i++) { string path = files.ElementAt(i); Dictionary<string, object> friendlyData = new Dictionary<string, object>(); // Embed the playlist index, since we could have multiple playlists queued up // which prevents us from being able to use MediaCollection.CurrentIndex friendlyData["FilePlaylistPosition"] = currentFileIndex.ToString(); // Embed the PlayableItemId so we can identify which one to track progress for friendlyData["PlayableItemId"] = playable.Id.ToString(); // Embed the Media index so we can identify which one to track progress for friendlyData["MediaIndex"] = mediaIndex.ToString(); // Set a friendly title friendlyData["Title"] = media.Name; var song = media as Song; if (song != null) { var itemImage = song.PrimaryImagePath; // The following "friendly" data fields are undocumented but working for song items... if (playable.Folder != null) { // This is either a music album or a playlist friendlyData["AlbumTitle"] = playable.Folder.Name; if (string.IsNullOrEmpty(itemImage)) { itemImage = playable.Folder.PrimaryImagePath; } } else { friendlyData["AlbumTitle"] = song.Album; } friendlyData["AlbumArtist"] = song.AlbumArtist; friendlyData["Artist"] = song.Artist; friendlyData["TrackNumber"] = currentFileIndex; if (song.PremierDate != DateTime.MinValue) { friendlyData["YearReleased"] = song.PremierDate.Year; } if (!string.IsNullOrEmpty(itemImage)) { friendlyData["AlbumCoverUrl"] = itemImage; } } coll.AddItem(path, collectionIndex, -1, string.Empty, friendlyData); currentFileIndex++; collectionIndex++; } } }
public static PlayableItem GetCurrentPlaybackItemUsingMetadataTitle(PlaybackController controllerInstance, IEnumerable<PlayableItem> playableItems, string metadataTitle, out int filePlaylistPosition, out int currentMediaIndex) { filePlaylistPosition = -1; currentMediaIndex = -1; metadataTitle = metadataTitle.ToLower(); // Loop through each PlayableItem and try to find a match foreach (PlayableItem playable in playableItems) { if (playable.HasMediaItems) { // The PlayableItem has Media items, so loop through each one and look for a match int totalFileCount = 0; int numMediaItems = playable.MediaItems.Count(); for (int i = 0; i < numMediaItems; i++) { Media media = playable.MediaItems.ElementAt(i); IEnumerable<string> files = controllerInstance.GetPlayableFiles(media); int index = PlaybackControllerHelper.GetIndexOfFileInPlaylist(files, metadataTitle); if (index != -1) { filePlaylistPosition = index + totalFileCount; currentMediaIndex = i; return playable; } totalFileCount += files.Count(); } } else { // There are no Media items so just find the index using the Files property int index = PlaybackControllerHelper.GetIndexOfFileInPlaylist(playable.FilesFormattedForPlayer, metadataTitle); if (index != -1) { filePlaylistPosition = index; return playable; } } } return null; }