private static void WaitForIsLoaded(IPlaylist playlist, CancellationToken cancellationToken)
 {
     while (!playlist.IsLoaded() || cancellationToken.IsCancellationRequested)
     {
         Task.Delay(250, cancellationToken);
     }
 }
 static SdkServices()
 {
     Playlist = new Playlist ();
     Player = (IPlayer)LoadService ("PlayerKits", configuration.PlayerKitType, configuration.PlayerKitAssembly);
     MusicDb = (IMusicDb) LoadService ("DataKits", configuration.DataKitType, configuration.DataKitAssembly);
     Player.Playlist = Playlist;
 }
 public GstPlayer(IPlaylist playlist)
 {
     this.playlist = playlist;
     player.TickEvent += TickCallback;
     player.EOSEvent += EosCallback;
     playing = false;
 }
Example #4
0
 public ErroneousTrack(ISession session, IntPtr handle, Error error, IPlaylist playlist = null)
     : base(session, handle)
 {
     _error = error;
     _playlist = playlist;
     _artists = new DelegateArray<IArtist>(() => 0, index => null);
 }
Example #5
0
        public Player()
        {
            _player = new WMPPlayer();
            _provider = new SoundCloudProvider();
            _playlist = new DummyPlaylist();

            _ui = new DasPlayer(this);

            // Hook up some _player events
            _player.StreamPlayerStateChanged += new PlayerStateChange(_player_StreamPlayerStateChanged);

            // Hook up playlist events
            _playlist.TrackChanged += new EventHandler(_playlist_TrackChanged);

            // Hook up some of the Player UI events
            _ui.ControlButtonPressed += new UIButtonEvent(ui_ControlButtonPressed);
            _ui.SearchRequested += new SearchRequested(_ui_SearchRequested);

            // Hook up the background worker for doing searches
            _bgSearch = new BackgroundWorker();
            _bgSearch.WorkerReportsProgress = false;
            _bgSearch.WorkerSupportsCancellation = false;
            _bgSearch.DoWork += new DoWorkEventHandler(_backgroundWorker_DoWork);
            _bgSearch.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_backgroundWorker_RunWorkerCompleted);

            // We're nice, we'll poll the timer for the UI and make sure it
            // gets notified when the progress changes
            _timer = new Timer();
            _timer.AutoReset = true;
            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
            _timer.SynchronizingObject = (Form)_ui; // dirty hackiness
        }
Example #6
0
 private Playlist(IPlaylist playlist)
 {
     this.playlist = playlist;
     Id = Guid.NewGuid();
     playlists.Add(Id, this);
     playlistIds.Add(playlist, Id);
 }
        protected PlaylistCommandBase(
            IPlaylist playlist, IMessenger messenger, IAudioPlayer player, Func<IPlaylist, Track> trackSelectFunc)
        {
            if (playlist == null)
            {
                throw new ArgumentNullException("playlist");
            }

            if (messenger == null)
            {
                throw new ArgumentNullException("messenger");
            }

            if (player == null)
            {
                throw new ArgumentNullException("player");
            }

            if (trackSelectFunc == null)
            {
                throw new ArgumentNullException("trackSelectFunc");
            }

            this.playlist = playlist;
            this.player = player;
            this.trackSelectFunc = trackSelectFunc;

            // Need to refresh after adding, removing, shuffling any tracks in
            // the mix. The prev/next track may no longer exist.
            messenger.Register<PlayerLoadedEvent>(this, OnMixChanged);
            messenger.Register<TrackAddedToMixEvent>(this, OnMixChanged);
            messenger.Register<TrackRemovedFromMixEvent>(this, OnMixChanged);
            messenger.Register<TracksRemovedFromMixEvent>(this, OnMixChanged);
            messenger.Register<MixUnlockedEvent>(this, OnMixChanged);
        }
		public int NextItem(IPlaylist playlist, int itemIndex) {
			if (itemIndex < 0)
				itemIndex = -1;

			if (playlist.IsRepeat)
				return itemIndex;

			if (playlist.IsRandom) {
				int lastIndex = itemIndex;
				if (playlist.Count > 1) {
					// continuously generate a random number
					// until you get one that was not the last...
					Random rand = new Random();
					while (itemIndex == lastIndex) {
						itemIndex = rand.Next(playlist.Count);
					}
				}
				return itemIndex;
			}

			int nextIndex = itemIndex + 1;

			if (nextIndex < playlist.Count) {
				return nextIndex;
			} else if (playlist.IsRewind) {
				return playlist.Count > 0 ? 0 : -1;
			} else {
				return -1;
			}
		}
Example #9
0
 public LoadingTitle(Standard w1,IPlaylist aPlaylist)
 {
     Owner = w1;
     InitializeComponent();
     _main = w1;
     _aPlaylist = aPlaylist;
 }
		public int PreviousItem(IPlaylist playlist, int itemIndex) {
			if (itemIndex > playlist.Count) {
				return playlist.Count - 1;
			}
			if (playlist.IsRepeat) {
				return itemIndex;
			}
			if (playlist.IsRandom) {
				Random rand = new Random();
				int lastIndex = itemIndex;
				// continuously generate a random number
				// until you get one that was not the last...
				while (itemIndex == lastIndex) {
					itemIndex = rand.Next(playlist.Count);
				}
				lastIndex = itemIndex;
				return itemIndex;
			}
			int prevIndex = itemIndex - 1;
			if (prevIndex >= 0) {
				return prevIndex;
			} else if (playlist.IsRewind) {
				return playlist.Count - 1;
			} else {
				return -1;
			}
		}
        //public PlaylistViewModel(IMediaItemController controller, IPlaylist playlist, IEnumerable<IPlaylistItemViewModel> playlistItems)
        //    : this(controller, playlist, playlistItems, "pack://application:,,,/Images/play-simple.png")
        //{
        //}

        public PlaylistViewModel(IMetadataController controller, IPlaylist playlist, IEnumerable<IPlaylistItemViewModel> playlistItems)
            : base(controller, playlist, "PLAYLIST", GetIcon(playlist))
        {
            if (playlistItems == null)
                throw new ArgumentNullException("playlistItems");

            this.playlistItems = new ObservableCollection<IPlaylistItemViewModel>(playlistItems);
            currentPlaylistItem = this.playlistItems.FirstOrDefault();
        }
Example #12
0
        public static Playlist ConvertToDto(IPlaylist playlist)
        {
            using(playlist)
            {
                playlist.WaitUntilLoaded();

                return Mapper.Map<IPlaylist, Playlist>(playlist);
            }
        }
 private string GetDownloadingStatusString(IPlaylist playlist)
 {
     if(playlist.OfflineStatus == PlaylistOfflineStatus.Downloading)
     {
         int status = playlist.OfflineDownloadProgress;
         return status + "%";
     }
     else
         return string.Empty;
 }
Example #14
0
        public SongPropertiesWindow(MainForm mainForm, Song song, int clickedIndex, IPlaylist currentPlaylist, Library library)
        {
            this.mainForm = mainForm;
            this.song = song;
            this.currentIndex = clickedIndex;
            this.currentPlaylist = currentPlaylist;
            this.library = library;

            InitializeComponent();
        }
        public bool Equals(IPlaylist other)
        {
            if (ReferenceEquals(other, null)) return false;
            if (ReferenceEquals(other, this)) return true;

            var sp = other as SpecialPlaylistBase;
            if (sp == null) return false;

            return sp.m_library == m_library && sp.m_type == m_type;
        }
        public MultiSongPropertiesWindow(MainForm mainForm, List<Song> songs, IPlaylist currentPlaylist, Library library)
        {
            this.mainForm = mainForm;
            this.songs = songs;
            this.currentPlaylist = currentPlaylist;
            this.library = library;
            this.saveProperties = new Dictionary<string, bool>();
            InitializeComponent();

            save_ComboBox.SelectedIndex = 0;
            for (int i = 2; i < save_ComboBox.Items.Count; i++)
                this.saveProperties.Add(save_ComboBox.Items[i].ToString(), false);
        }
Example #17
0
 internal PlayerContext(IPlayerSlotController slotController, Guid mediaModuleId, string name, AVType type,
     Guid currentlyPlayingWorkflowStateId, Guid fullscreenContentWorkflowStateId)
 {
   _slotController = slotController;
   _slotController.Closed += OnClosed;
   SetContextVariable(KEY_PLAYER_CONTEXT, this);
   _playlist = new Playlist(this);
   _mediaModuleId = mediaModuleId;
   _name = name;
   _type = type;
   _currentlyPlayingWorkflowStateId = currentlyPlayingWorkflowStateId;
   _fullscreenContentWorkflowStateId = fullscreenContentWorkflowStateId;
 }
Example #18
0
 public void PlaylistChanged(IPlaylist NewPlaylist)
 {
     foreach (var child in PlaylistItemStack.Children.OfType<JwPlaylistItem>()) {
         child.Clicked -= button_Clicked;
     }
     PlaylistItemStack.Children.Clear();
     SetScroll(0);
     foreach (var item in NewPlaylist.Items) {
         var button = new JwPlaylistItem { PlaylistItem = item };
         button.Clicked +=button_Clicked;
         PlaylistItemStack.Children.Add(button);
     }
     BindSkins();
 }
 private string GetPlaylistStatusString(IPlaylist playlist)
 {
     switch (playlist.OfflineStatus)
     {
         case PlaylistOfflineStatus.Downloading:
             return "downloading";
         case PlaylistOfflineStatus.No:
             return "online";
         case PlaylistOfflineStatus.Waiting:
             return "queued";
         case PlaylistOfflineStatus.Yes:
             return "offline";
         default:
             throw new Exception("Unrecognized playlist state");
     }
 }
Example #20
0
        public Playlist(IPlaylist playlist, Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;
            _tracks = new NotifyCollection<PlaylistTrack>();

            InternalPlaylist = playlist;
            InternalPlaylist.DescriptionChanged += OnDescriptionChanged;
            InternalPlaylist.MetadataUpdated += OnMetadataChanged;
            InternalPlaylist.Renamed += OnRenamed;
            InternalPlaylist.StateChanged += OnStateChanged;
            InternalPlaylist.TracksAdded += OnTracksAdded;
            InternalPlaylist.TracksRemoved += OnTracksRemoved;
            InternalPlaylist.TracksMoved += OnTracksMoved;
            InternalPlaylist.UpdateInProgress += OnUpdateInProgress;

            _isLoaded = InternalPlaylist.IsLoaded;

            if (_isLoaded)
            {
                FetchTracks();
            }
        }
Example #21
0
    /*
     * Main constructor
     */
    public GstPlayer(IPlaylist playlist)
        : base(IntPtr.Zero)
    {
        this.playlist = playlist;
        IntPtr error_ptr;

        Raw = player_new (out error_ptr);
        if (error_ptr != IntPtr.Zero) {
            string error = GLib.Marshaller.PtrToStringGFree (error_ptr);

            throw new Exception (error);
        }

        ConnectInt.g_signal_connect_data (Raw, "tick", new IntSignalDelegate (TickCallback),
                          IntPtr.Zero, IntPtr.Zero, 0);
        Connect.g_signal_connect_data (Raw, "end_of_stream", new SignalDelegate (EosCallback),
                       IntPtr.Zero, IntPtr.Zero, 0);
        ConnectString.g_signal_connect_data (Raw, "error", new StringSignalDelegate (ErrorCallback),
                         IntPtr.Zero, IntPtr.Zero, 0);

        playing = false;
    }
Example #22
0
        public static async Task <bool> SavePlaylist(Playlist playlist, IEnumerable <Mediafile> songs)
        {
            bool           saved  = false;
            FileSavePicker picker = new FileSavePicker();

            picker.FileTypeChoices.Add("PLS Playlists", new List <string> {
                ".pls"
            });
            picker.FileTypeChoices.Add("M3U Playlists", new List <string> {
                ".m3u"
            });
            picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
            picker.SuggestedFileName      = playlist.Name;

            await BreadDispatcher.InvokeAsync(async() =>
            {
                var file = await picker.PickSaveFileAsync();
                if (file != null)
                {
                    IPlaylist sPlaylist = null;
                    switch (file.FileType.ToLower())
                    {
                    case ".m3u":
                        sPlaylist = new M3U();
                        break;

                    case ".pls":
                        sPlaylist = new Pls();
                        break;
                    }
                    saved = await sPlaylist.SavePlaylist(songs, await file.OpenStreamForWriteAsync().ConfigureAwait(false)).ConfigureAwait(false);
                }
            });

            return(saved);
        }
        /// <summary>
        /// Adds some tracks to an iTunes playlist.
        /// </summary>
        /// <param name="playlist">The playlist to modify</param>
        /// <param name="playlistLines">The tracks to add to iTunes as represented by their device location.</param>
        /// <param name="searchHint">
        /// A playlist folder to look in. This will reduce the search time.
        /// This only works under the assumption that all music that can possibly be on the device are under this folder.
        /// Use "Music" to search all songs.
        /// </param>
        /// <param name="root">The root device path used to generate device location. This should be the same root used to generate "playlistLines"</param>
        /// <returns>An enumeration of all songs that were successfully added to the playlist.</returns>
        public IEnumerable<string> AddTracks(IPlaylist playlist, IEnumerable<string> playlistLines, ISubscription subscription, string root)
        {
            List<string> addedTracks = new List<string>();

            IITUserPlaylist targetPlaylist = playlistLookupTable[playlist.GetSafeName()] as IITUserPlaylist;

            if (targetPlaylist == null) return addedTracks;

            var subscribedTracks = GetSubscribedTracks(subscription);

            foreach (var line in playlistLines)
            {
                foreach (var iTrack in subscribedTracks)
                {
                    if (line != iTrack.GetPlaylistLine(root)) continue;

                    targetPlaylist.AddTrack(iTrack);
                    addedTracks.Add(line);
                    break;
                }
            }

            return addedTracks;
        }
Example #24
0
 public static void Assign(IConfig config, ISettings settings, IThemes themes, ILog log, IBackgroundMusic backgroundMusic,
                           IDrawing draw, IGraphics graphics, IFonts fonts, ILanguage language, IGame game, IProfiles profiles, IRecording record,
                           ISongs songs, IVideo video, ISound sound, ICover cover, IDataBase dataBase, IControllers controller, IPlaylist playlist)
 {
     Config          = config;
     Settings        = settings;
     Themes          = themes;
     Log             = log;
     BackgroundMusic = backgroundMusic;
     Drawing         = draw;
     Graphics        = graphics;
     Fonts           = fonts;
     Language        = language;
     Game            = game;
     Profiles        = profiles;
     Record          = record;
     Songs           = songs;
     Video           = video;
     Sound           = sound;
     Cover           = cover;
     DataBase        = dataBase;
     Controller      = controller;
     Playlist        = playlist;
 }
Example #25
0
        public static void ChangeCurrentSong(this IPlaylist playlist, int offset)
        {
            int count = playlist.Songs.Shuffle.Count;

            if (count == 0)
            {
                return;
            }

            int shuffleSongsIndex = playlist.Songs.Shuffle.IndexOf(playlist.CurrentSong);

            shuffleSongsIndex    = (shuffleSongsIndex + offset + count) % count;
            playlist.CurrentSong = playlist.Songs.Shuffle.ElementAt(shuffleSongsIndex);

            if (playlist.CurrentSong.Failed)
            {
                if (playlist.Songs.All(x => x.Failed))
                {
                    return;
                }

                ChangeCurrentSong(playlist, offset);
            }
        }
Example #26
0
        public async Task ReorderPlaylist(IPlaylist playlist, Room room)
        {
            try
            {
                var client = new RestClient(@"https://api.spotify.com/v1");
                client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator($"Bearer {AuthToken}");
                var request = new RestRequest($@"playlists/{playlist.PlaylistID}/tracks", Method.PUT);
                request.RequestFormat = DataFormat.Json;

                var spotifyUris = room.RoomSongs
                                  .OrderByDescending(s => s.SongRating)
                                  .Select(s => s.Song.ServiceId)
                                  .ToList();

                // Move the currently playing song to the top of the playlist
                // to ensure that the next song played is the highest rated
                // regardless of re-orders
                var currentSong = await GetCurrentlyPlayingSongAsync();

                if (currentSong != null)
                {
                    spotifyUris.Remove(currentSong.Item.Uri);
                    spotifyUris.Insert(0, currentSong.Item.Uri);
                }

                request.AddJsonBody(new { uris = spotifyUris });

                var response = await client.ExecuteAsync(request);

                var content = response.Content;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #27
0
        /// <summary>
        /// generate a playlist
        /// </summary>
        /// <param name="control">control file to use to find the podcasts and playlist format</param>
        /// <param name="rootFolder">root folder to find episodes</param>
        /// <param name="copyToDestination">true to copy the playlist to the root folder, false to write it with the control file</param>
        private void GeneratePlaylist(IReadOnlyControlFile control, string rootFolder, bool copyToDestination)
        {
            IEnumerable <IFileInfo> allDestFiles = control.GetPodcasts().SelectMany(
                podcast => FileFinder.GetFiles(Path.Combine(rootFolder, podcast.Folder), podcast.Pattern.Value));
            List <IFileInfo> allDestFilesSorted = allDestFiles.OrderBy(item => item.FullName).ToList();

            IPlaylist p = PlaylistFactory.CreatePlaylist(control.GetPlaylistFormat(), control.GetPlaylistFileName());

            string pathSeparator = PathUtilities.GetPathSeparator().ToString();

            foreach (IFileInfo thisFile in allDestFilesSorted)
            {
                string thisRelativeFile = thisFile.FullName;
                string absRoot          = PathUtilities.GetFullPath(rootFolder);
                if (thisRelativeFile.StartsWith(absRoot, StringComparison.Ordinal))
                {
                    thisRelativeFile = thisRelativeFile.Substring(absRoot.Length);
                }
                thisRelativeFile = thisRelativeFile.Replace(pathSeparator, control.GetPlaylistPathSeparator());
                p.AddTrack("." + thisRelativeFile);
            }

            var tempFile = PathUtilities.GetTempFileName();

            OnStatusUpdate(string.Format(CultureInfo.InvariantCulture, "Generating Playlist with {0} items", p.NumberOfTracks), false);

            p.SaveFile(tempFile);

            var destPlaylist = copyToDestination
                                   ? Path.Combine(rootFolder, control.GetPlaylistFileName())
                                   : control.GetPlaylistFileName();

            OnStatusUpdate(string.Format(CultureInfo.InvariantCulture, "Writing playlist to {0}", destPlaylist), true);

            FileUtilities.FileCopy(tempFile, destPlaylist, true);
        }
        internal static IPlaylistTrack Get(ISession session, IPlaylist playlist, IntPtr trackPointer, int position)
        {
            KeyGen key = new KeyGen(playlist, position);

            lock (_tracksLock)
            {
                IPlaylistTrack instance;

                if (!_instances.TryGetValue(key, out instance))
                {
                    var newInstance = new NativePlaylistTrack(session, trackPointer, playlist, position);

                    if (SessionFactory.IsInternalCachingEnabled)
                    {
                        _instances.Add(key, newInstance);
                    }

                    newInstance.Initialize();
                    instance = newInstance;

                    Error error = instance.Error;
                    if (error != Error.OK && error != Error.IsLoading)
                    {
                        instance.Dispose();
                        instance = null;

                        if (SessionFactory.IsInternalCachingEnabled)
                        {
                            _instances[key] = instance = new ErroneousTrack(session, trackPointer, error, playlist);
                        }
                    }
                }

                return(instance);
            }
        }
        protected void UpdateCurrentItem()
        {
            IPlayerContextManager playerContextManager = ServiceRegistration.Get <IPlayerContextManager>();
            IPlayerContext        pc       = playerContextManager.GetPlayerContext(PlayerChoice.CurrentPlayer);
            IPlaylist             playlist = pc == null ? null : pc.Playlist;

            lock (_syncObj)
                if (playlist == null || playlist != _playlist)
                {
                    return;
                }
            int idx = playlist.ItemListIndex;

            foreach (PlayableMediaItem item in _playlistItems)
            {
                bool isCurrentItem        = idx-- == 0;
                bool?currentIsCurrentItem = (bool?)item.AdditionalProperties[Consts.KEY_IS_CURRENT_ITEM];
                if (isCurrentItem != (currentIsCurrentItem ?? false))
                {
                    item.AdditionalProperties[Consts.KEY_IS_CURRENT_ITEM] = isCurrentItem;
                    item.FireChange();
                }
            }
        }
        protected void UpdatePlaylist()
        {
            IPlayerContextManager playerContextManager = ServiceRegistration.Get <IPlayerContextManager>();
            IPlayerContext        pc       = playerContextManager.GetPlayerContext(PlayerChoice.CurrentPlayer);
            IPlaylist             playlist = pc == null ? null : pc.Playlist;

            UpdatePlaylistHeader(pc == null ? null : (AVType?)pc.AVType, pc == null ? 0 : pc.PlayerSlotController.SlotIndex);
            lock (_syncObj)
            {
                // TODO: If playlist objects differ, leave state EditPlaylist?
                _playlist = playlist;
                _items.Clear();
                if (playlist != null)
                {
                    IList <MediaItem> items = playlist.ItemList;
                    for (int i = 0; i < items.Count; i++)
                    {
                        MediaItem         mediaItem = items[i];
                        PlayableMediaItem item      = PlayableMediaItem.CreateItem(mediaItem);

                        item.SetLabel(Consts.KEY_NUMBERSTR, (i + 1) + ".");
                        item.AdditionalProperties[Consts.KEY_INDEX] = i;

                        item.AdditionalProperties[Consts.KEY_IS_DOWN_BUTTON_FOCUSED] = i == _focusedDownButton;
                        item.AdditionalProperties[Consts.KEY_IS_UP_BUTTON_FOCUSED]   = i == _focusedUpButton;
                        item.AdditionalProperties[Consts.KEY_INDEX] = i;
                        _items.Add(item);
                    }
                }
                _focusedDownButton  = -1;
                _focusedUpButton    = -1;
                IsPlaylistEmpty     = _items.Count == 0;
                NumPlaylistItemsStr = Utils.BuildNumItemsStr(_items.Count, null);
            }
            _items.FireChange();
        }
Example #31
0
        private async void btnFindPlaylist_Click(object sender, EventArgs e)
        {
            try
            {
                _playlists = (await _deezer.User.Current.GetPlaylists(250)).ToList();
                var test = _playlists.FirstOrDefault(p => p.IsLovedTrack);

                _playlist = _playlists.FirstOrDefault(p => p.Title.ToLower() == txtPlaylist.Text.ToLower());

                if (_playlist == null)
                {
                    AddToLog("Playlist not found !");
                }
                else
                {
                    AddToLog("Playlist found.");
                    txtPlaylist.Text = _playlist.Title;
                }
            }
            catch (Exception v_ex)
            {
                MessageBox.Show(v_ex.ToString());
            }
        }
Example #32
0
 public void TearDown()
 {
     playlist = null;
 }
Example #33
0
 public HomeController(IPlaylist playlist, IErrorLoggingService error, IPlaylistService playlistsService,
                       ICloudService cloudService, ILastFmApiClientService lastFm, IPlaySettings playSettings)
     : base(cloudService, playlist, error, playSettings)
 {
     _lastFm = lastFm;
 }
Example #34
0
 private void PlayASong(ISong song, IPlaylist currentPlaylist)
 {
     _currentSong = song;
     _player.Open(new Uri(song.Path));
     SongTitle = song.Title;
     _player.Play();
     _dispatcherTimer.IsEnabled = true;
     Status = PlayStatus.Playing;
 }
Example #35
0
 public async Task PlayAsync(IPlaylist playlist)
 {
     await this.PlayAsync(playlist, songIndex : -1);
 }
Example #36
0
 private void WriteToFile(string id, IPlaylist list)
 {
     WriteToFile(IdToFile(id), list);
 }
Example #37
0
 public WplPlaylist(IPlaylist playlist) : base(playlist)
 {
 }
 private static object GetIcon(IPlaylist playlist)
 {
     return(playlist.ThumbnailData != null && playlist.ThumbnailData.Length > 0 ? playlist.ThumbnailData : (object)playlist.Thumbnail);
 }
Example #39
0
        private async Task PublishAsync(Song song, IPlaylist currentPlaylist, CancellationToken cancellationToken)
        {
            if (this.logger.IsDebugEnabled)
            {
                this.logger.Debug("PublishAsync: Add new task for publishing: ProviderSongId: {0}, PlaylistType: {1}.", song.ProviderSongId, currentPlaylist == null ? null : currentPlaylist.GetType());
            }

            Task <Uri> getAlbumArtTak = this.GetAlbumArtUri(song);

            cancellationToken.ThrowIfCancellationRequested();

            Task immediately = Task.Factory.StartNew(
                async() =>
            {
                Task withoutAlbumArt = this.PublishAsync(
                    this.songPublishers.Where(x => x.Value.PublisherType == PublisherType.Immediately),
                    song,
                    currentPlaylist,
                    null,
                    cancellationToken);

                Uri albumArt = await getAlbumArtTak;

                Task withAlbumArt = this.PublishAsync(
                    this.songPublishers.Where(x => x.Value.PublisherType == PublisherType.ImmediatelyWithAlbumArt),
                    song,
                    currentPlaylist,
                    albumArt,
                    cancellationToken);

                await Task.WhenAll(withAlbumArt, withoutAlbumArt);
            });

            cancellationToken.ThrowIfCancellationRequested();

            var delayPublishers =
                this.songPublishers.Where(
                    x => x.Value.PublisherType == PublisherType.Delay || x.Value.PublisherType == PublisherType.DelayWithAlbumArt).ToList();

            if (!delayPublishers.Any())
            {
                this.logger.Debug("PublishAsync: no delay publishers, return.", song.ProviderSongId, currentPlaylist == null ? null : currentPlaylist.GetType());
                return;
            }

            await Task.Delay(Math.Min(this.delayPublishersHoldUp, (int)(0.3 * song.Duration.TotalMilliseconds)), cancellationToken);

            cancellationToken.ThrowIfCancellationRequested();

            Task delay = Task.Factory.StartNew(
                async() =>
            {
                Task withoutAlbumArt = this.PublishAsync(
                    this.songPublishers.Where(x => x.Value.PublisherType == PublisherType.Delay),
                    song,
                    currentPlaylist,
                    null,
                    cancellationToken);

                Uri albumArt = await getAlbumArtTak;

                Task withAlbumArt = this.PublishAsync(
                    this.songPublishers.Where(x => x.Value.PublisherType == PublisherType.DelayWithAlbumArt),
                    song,
                    currentPlaylist,
                    albumArt,
                    cancellationToken);

                await Task.WhenAll(withAlbumArt, withoutAlbumArt);
            });

            cancellationToken.ThrowIfCancellationRequested();

            await Task.WhenAll(immediately, delay);

            this.logger.Debug("PublishAsync completed for ProviderSongId: {0}, PlaylistType: {1}.", song.ProviderSongId, currentPlaylist == null ? null : currentPlaylist.GetType());
        }
Example #40
0
 public TrackPlaylistPair(PlayableBase track, IPlaylist playlist)
 {
     Track    = track;
     Playlist = playlist;
 }
Example #41
0
 public void LoadPlaylist(IPlaylist playlist)
 {
     _queue = new PlaylistQueue(playlist);
     LoadTrack(0);
 }
Example #42
0
 public void PlaylistChanged(IPlaylist NewPlaylist)
 {
 }
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     DataContext = viewModel = e.Parameter as IPlaylist;
 }
Example #44
0
 public Task SavePlaylist(IPlaylist playlist)
 {
     //_barrel.Add<IPlaylist>(playlist.Id.ToString(), playlist, TimeSpan.MaxValue);
     return(Task.CompletedTask);
 }
Example #45
0
 public ArtistController(IPlaylist playlist, IErrorLoggingService logger, ICloudService cloudService, IPlaySettings playSettings)
     : base(cloudService, playlist, logger, playSettings)
 {
 }
Example #46
0
 public void RunAsync(IPlaylist lst)
 {
     PlaylistsToCheck.Add(lst);
     Run();
 }
Example #47
0
 private async Task PublishAsync(IEnumerable <Lazy <ICurrentSongPublisher> > publishers, Song song, IPlaylist currentPlaylist, Uri albumArtUri, CancellationToken cancellationToken)
 {
     await Task.WhenAll(publishers.Select(x => x.Value.PublishAsync(song, currentPlaylist, albumArtUri, cancellationToken)).Where(task => task != null));
 }
Example #48
0
 private void StartBackgroundMusic()
 {
     if (Playlist != null) {
         Playlist.Stop ();
     }
     Log.Debug ("Background Music: ", BackgroundMusic);
     if (AudioFiles.ContainsKey (BackgroundMusic)) {
         Playlist = new LoopPlaylist (AudioFiles [BackgroundMusic]);
         Playlist.Shuffle ();
         Playlist.Start ();
     }
     else {
         Log.Message ("Warning: ", BackgroundMusic, ": no sound files available!");
     }
 }
Example #49
0
 public Task <bool> RemovePlaylistFromFavourite(IPlaylist aPlaylist)
 => RemovePlaylistFromFavourite(aPlaylist.Id);
Example #50
0
        private async Task OpenPlayable(IPlayable playable, IPlaylist playlist, bool openPlaying, bool openCrossfading, bool addToTempHistory)
        {
            _isOpeningTrack = true;
            if (CurrentTrack != null)
                TrackChanged?.Invoke(this, new TrackChangedEventArgs(CurrentTrack, AudioEngine.TimePlaySourcePlayed));
            CurrentTrack = playable;
            CurrentPlaylist = playlist;

            if (await AudioEngine.OpenTrack(await playable.GetSoundSource(), IsCrossfadeEnabled && openCrossfading, 0))
            {
                var track = playable as PlayableBase;
                if (track != null)
                    playlist?.GetBackHistory().Add(track);

                NewTrackOpened?.Invoke(this, new NewTrackOpenedEventArgs(playable));

                if (addToTempHistory && (_tempHistory.Count == 0 || _tempHistory.Last().Item1 != playlist || _tempHistory.Last().Item2 != playable))
                    _tempHistory.Add(Tuple.Create(playlist, playable));

                if (openPlaying && !(IsCrossfadeEnabled && openCrossfading))
                    await AudioEngine.TogglePlayPause();
            }
            _isOpeningTrack = false;
        }
Example #51
0
        /// <summary>
        /// Provides a callable method for the skin to set the time of the sleeptimer
        /// to the length of the current playlist
        /// </summary>
        public void FromPlaylist()
        {
            try
            {
                IPlayerContextManager playerContextManager = ServiceRegistration.Get <IPlayerContextManager>();
                if (playerContextManager == null)
                {
                    return;
                }
                IPlayerContext playerContext = playerContextManager.CurrentPlayerContext;
                if (playerContext == null)
                {
                    return;
                }

                IPlaylist playlist = playerContext.Playlist;
                if (playlist == null)
                {
                    return;
                }

                // playlistTime
                TimeSpan  playlistDuration = new TimeSpan();
                MediaItem item;
                for (int i = 0; (item = playlist[i]) != null; i++)
                {
                    IList <MediaItemAspect> aspects;
                    if (item.Aspects.TryGetValue(AudioAspect.ASPECT_ID, out aspects))
                    {
                        var      aspect = aspects.First();
                        long?    dur    = aspect == null ? null : (long?)aspect[AudioAspect.ATTR_DURATION];
                        TimeSpan miDur  = dur.HasValue ? TimeSpan.FromSeconds(dur.Value) : TimeSpan.FromSeconds(0);
                        playlistDuration = playlistDuration.Add(miDur);
                    }
                    else if (item.Aspects.TryGetValue(VideoStreamAspect.ASPECT_ID, out aspects))
                    {
                        var  aspect  = aspects.First();
                        int? part    = (int?)aspect[VideoStreamAspect.ATTR_VIDEO_PART];
                        int? partSet = (int?)aspect[VideoStreamAspect.ATTR_VIDEO_PART_SET];
                        long?dur     = null;
                        if (!part.HasValue || part < 0)
                        {
                            dur = (long?)aspect[VideoStreamAspect.ATTR_DURATION];
                        }
                        else if (partSet.HasValue)
                        {
                            dur = aspects.Where(a => (int?)a[VideoStreamAspect.ATTR_VIDEO_PART_SET] == partSet &&
                                                aspect[VideoStreamAspect.ATTR_DURATION] != null).Sum(a => (long)a[VideoStreamAspect.ATTR_DURATION]);
                        }
                        TimeSpan miDur = dur.HasValue ? TimeSpan.FromSeconds(dur.Value) : TimeSpan.FromSeconds(0);
                        playlistDuration = playlistDuration.Add(miDur);
                    }
                }

                // currentTime
                IPlayer player = playerContext.CurrentPlayer;
                IMediaPlaybackControl control = player as IMediaPlaybackControl;
                if (control == null)
                {
                    return;
                }

                TimeSpan duration = playlistDuration.Subtract(control.CurrentTime);
                int      minutes  = (int)duration.TotalMinutes;
                // Add 1 extra Minute to ensure, that the player finished
                minutes       += 1;
                InitialMinutes = minutes;
            }
            catch (Exception)
            {
                // nur zur Sicherheit
            }
        }
Example #52
0
 public Task OpenPlayable(IPlayable playable, IPlaylist playlist)
 {
     return OpenPlayable(playable, playlist, true, false, true);
 }
Example #53
0
        public void PlaySong(ISong song, IPlaylist currentPlaylist)
        {
            if(currentPlaylist == null)
            {
                return;
            }
            if(song == null)
            {
                song = currentPlaylist.Songs.First();
            }

            if(Status == PlayStatus.Paused)
            {
                _player.Play();
                _dispatcherTimer.IsEnabled = true;
                Status = PlayStatus.Playing;

            }
            else if(Status == PlayStatus.Stopped)
            {
                PlayASong(song, currentPlaylist);
                CurrentPlaylist = currentPlaylist;
            }
            else if (CurrentPlaylist != currentPlaylist)
            {
                PlayASong(song, currentPlaylist);
                CurrentPlaylist = currentPlaylist;
            }
        }
Example #54
0
 public Task OpenPlayable(IPlayable playable, IPlaylist playlist, bool openPlaying)
 {
     return OpenPlayable(playable, playlist, openPlaying, false, true);
 }
Example #55
0
 public void Innit()
 {
     _fixture = new Playlist.Playlist("playlistname", "authorname", new DateTime(2000, 12, 24));
 }
 public void PlaylistChanged(IPlaylist NewPlaylist)
 {
 }
Example #57
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RandomizedPlaylistEnumerator"/> class.
 /// </summary>
 /// <param name="playlist">The playlist.</param>
 public RandomizedPlaylistEnumerator(IPlaylist playlist)
     : base(playlist)
 {
     this.RandomizeIndexes();
 }
Example #58
0
 public MainController(IPlaylist playlist)
 {
     _playlist = playlist;
 }
Example #59
0
 public ArtistController(UserManager <DbUser> userManager, IUser myUser, ITreck trecks, IPlaylist playlists, IPlaylistTreck playlistsTreck, IGenres genres, IAlbums albums, IArtist artist)
 {
     _userManager    = userManager;
     _myUser         = myUser;
     _trecks         = trecks;
     _playlists      = playlists;
     _playlistsTreck = playlistsTreck;
     _genres         = genres;
     _albums         = albums;
     _artist         = artist;
 }
Example #60
0
 public static WplProvider <V> Create <V>(IPlaylist <V> playlist)
     where V : IMedia
 {
     return(new WplProvider <V>(playlist));
 }