Beispiel #1
0
        public async Task <IEnumerable <Mediafile> > LoadPlaylist(StorageFile file)
        {
            using (var streamReader = new StreamReader(await file.OpenStreamForReadAsync()))
            {
                List <Mediafile> playlistSongs = new List <Mediafile>();
                string           line;
                int  index       = 0;
                int  failedFiles = 0;
                bool ext         = false;
                while ((line = streamReader.ReadLine()) != null)
                {
                    if (line.ToLower() == "#extm3u") //m3u header
                    {
                        ext = true;
                    }
                    else if (ext && line.ToLower().StartsWith("#extinf:")) //extinfo of each song
                    {
                        continue;
                    }
                    else if (line.StartsWith("#") || line == "") //pass blank lines
                    {
                        continue;
                    }
                    else
                    {
                        await Task.Run(async() =>
                        {
                            try
                            {
                                index++;
                                FileInfo info = new FileInfo(file.Path);  //get playlist file info to get directory path
                                string path   = line;
                                if (!File.Exists(line) && line[1] != ':') // if file doesn't exist then perhaps the path is relative
                                {
                                    path = info.DirectoryName + line;     //add directory path to song path.
                                }

                                var accessFile = await StorageFile.GetFileFromPathAsync(path);
                                var token      = StorageApplicationPermissions.FutureAccessList.Add(accessFile);

                                Mediafile mp3File = await SharedLogic.CreateMediafile(accessFile); //prepare Mediafile

                                await SettingsViewModel.SaveSingleFileAlbumArtAsync(mp3File, accessFile);
                                playlistSongs.Add(mp3File);
                                StorageApplicationPermissions.FutureAccessList.Remove(token);
                            }
                            catch
                            {
                                failedFiles++;
                            }
                        });
                    }
                }
                return(playlistSongs);
            }
        }
        /// <summary>
        /// Asynchronously saves all the album arts in the library.
        /// </summary>
        /// <param name="Data">ID3 tag of the song to get album art data from.</param>
        public static async Task <bool> SaveAlbumArtsAsync(StorageFile file, Mediafile mediafile)
        {
            var albumArt = AlbumArtFileExists(mediafile);

            if (!albumArt.NotExists)
            {
                return(false);
            }

            try
            {
                using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 512, ThumbnailOptions.ReturnOnlyIfCached))
                {
                    if (thumbnail == null && file.IsAvailable)
                    {
                        using (TagLib.File tagFile = TagLib.File.Create(new SimpleFileAbstraction(file), TagLib.ReadStyle.Average))
                        {
                            if (tagFile.Tag.Pictures.Length >= 1)
                            {
                                var image = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"AlbumArts\" + albumArt.FileName + ".jpg", CreationCollisionOption.FailIfExists);

                                using (FileStream stream = new FileStream(image.Path, FileMode.Open, FileAccess.Write, FileShare.None, 51200, FileOptions.WriteThrough))
                                {
                                    await stream.WriteAsync(tagFile.Tag.Pictures[0].Data.Data, 0, tagFile.Tag.Pictures[0].Data.Data.Length);
                                }
                                return(true);
                            }
                        }
                    }
                    else if (thumbnail != null)
                    {
                        var albumart = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"AlbumArts\" + albumArt.FileName + ".jpg", CreationCollisionOption.FailIfExists);

                        IBuffer buf;
                        Windows.Storage.Streams.Buffer inputBuffer = new Windows.Storage.Streams.Buffer((uint)thumbnail.Size / 2);
                        using (IRandomAccessStream albumstream = await albumart.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            while ((buf = await thumbnail.ReadAsync(inputBuffer, inputBuffer.Capacity, InputStreamOptions.ReadAhead)).Length > 0)
                            {
                                await albumstream.WriteAsync(buf);
                            }

                            return(true);
                        }
                    }
                }
            }
#pragma warning disable CS0168 // The variable 'ex' is declared but never used
            catch (Exception ex)
#pragma warning restore CS0168 // The variable 'ex' is declared but never used
            {
                //await SharedLogic.Instance.NotificationManager.ShowMessageAsync(ex.Message + "||" + file.Path);
            }

            return(false);
        }
Beispiel #3
0
        public async Task <IActionResult> Index()
        {
            var content          = "";
            var currentTeacherId = Request.Cookies["teacher"]; // also in BaseController


            // upload media file with associated teacher

            if (Request.Method == "POST" && Request.Form.Files.Count > 0)
            {
                var uploadedFile = Request.Form.Files[0];
                var mediafile    = new Mediafile
                {
                    OriginalFileName = uploadedFile.FileName,
                    Title            = uploadedFile.FileName,
                    ContentType      = uploadedFile.ContentType,
                    TeacherId        = currentTeacherId
                };
                var mediafileId = await firestoreProvider.AddMediafileAsync(mediafile);

                using (var memoryStream = new MemoryStream())
                {
                    await uploadedFile.CopyToAsync(memoryStream);

                    var obj = new Storagefile
                    {
                        Name        = mediafileId,              // Path.GetExtension if we want the .mp4
                        ContentType = uploadedFile.ContentType, // content type is set so we don't really need the extension
                        Metadata    = new Dictionary <string, string>
                        {
                            { "OriginalFileName", uploadedFile.FileName }
                        }
                    };
                    var upload = await storageProvider.UploadObjectAsync(obj, memoryStream);

                    ViewBag.uploadedData = upload;
                }
            }


            // display list of media files for current teacher

            if (!String.IsNullOrEmpty(currentTeacherId))
            {
                var listFiles = await firestoreProvider.GetMediafilesByTeacherIdAsync(currentTeacherId);

                listFiles.Select(c => { c.HumanTime = Utility.RelativeDate(c.CreatedDateTime); return(c); }).ToList();
                listFiles.Sort((y, x) => DateTime.Compare(x.CreatedDateTime, y.CreatedDateTime)); // newest first
                ViewBag.listFiles  = listFiles;
                ViewBag.bucketName = storageProvider.bucketName;
            }


            ViewBag.content = content;
            return(View());
        }
Beispiel #4
0
        /// <summary>
        /// Loads the specified file into the player.
        /// </summary>
        /// <param name="fileName">Path to the music file.</param>
        /// <returns>Boolean</returns>
        public async Task <bool> Load(Mediafile mediaFile)
        {
            if (mediaFile != null && mediaFile.Length != "00:00")
            {
                try
                {
                    await InitializeCore.Dispatcher.RunAsync(() => { MediaChanging?.Invoke(this, new EventArgs()); });

                    string path = mediaFile.Path;
                    await Stop();

                    await Task.Run(() =>
                    {
                        _handle               = Bass.CreateStream(path, 0, 0, BassFlags.AutoFree | BassFlags.Float);
                        PlayerState           = PlayerState.Stopped;
                        Length                = 0;
                        Length                = Bass.ChannelBytes2Seconds(_handle, Bass.ChannelGetLength(_handle));
                        Bass.FloatingPointDSP = true;
                        Bass.ChannelSetSync(_handle, SyncFlags.End | SyncFlags.Mixtime, 0, _sync);
                        Bass.ChannelSetSync(_handle, SyncFlags.Position, Bass.ChannelSeconds2Bytes(_handle, Length - 5), _posSync);
                        Bass.ChannelSetSync(_handle, SyncFlags.Position, Bass.ChannelSeconds2Bytes(_handle, Length - 15), _posSync);

                        CurrentlyPlayingFile = mediaFile;
                    });

                    if (Equalizer == null)
                    {
                        Equalizer = new BassEqualizer(_handle);
                    }
                    else
                    {
                        (Equalizer as BassEqualizer).ReInit(_handle);
                    }
                    MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(PlayerState.Stopped));

                    return(true);
                }
                catch (Exception ex)
                {
                    await InitializeCore.NotificationManager.ShowMessageAsync(ex.Message + "||" + mediaFile.OrginalFilename);
                }
            }
            else
            {
                string error = "The file " + mediaFile.OrginalFilename + " is either corrupt, incomplete or unavailable. \r\n\r\n Exception details: No data available.";
                if (IgnoreErrors)
                {
                    await InitializeCore.NotificationManager.ShowMessageAsync(error);
                }
                else
                {
                    await InitializeCore.NotificationManager.ShowMessageBoxAsync(error, "File corrupt");
                }
            }
            return(false);
        }
Beispiel #5
0
        public static async Task <Mediafile> CreateMediafile(StorageFile file)
        {
            CurrentFileToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
            var Mediafile = new Mediafile();

            Mediafile._id = LiteDB.ObjectId.NewObjectId();
            //using (Stream stream = await file.OpenStreamForWriteAsync())
            //{
            //    ID3v2 Data = new ID3v2(true, stream);
            //    Mediafile._id = LiteDB.ObjectId.NewObjectId();
            //    Mediafile.Path = file.Path;
            //    Mediafile.Title = GetStringForNullOrEmptyProperty((await LibVM.GetTextFrame(Data, "TIT2")), System.IO.Path.GetFileNameWithoutExtension(LibraryViewModel.Path));
            //    Mediafile.LeadArtist = GetStringForNullOrEmptyProperty((await LibVM.GetTextFrame(Data, "TPE1")), "Unknown Artist");
            //    Mediafile.Album = GetStringForNullOrEmptyProperty((await LibVM.GetTextFrame(Data, "TALB")), "Unknown Album");
            //    Mediafile.State = PlayerState.Stopped;
            //    var genre = (await LibVM.GetTextFrame(Data, "TCON"));
            //    Mediafile.Genre = genre.Remove(0, (genre).IndexOf(')') + 1);
            //    Mediafile.Year = GetStringForNullOrEmptyProperty((await LibVM.GetTextFrame(Data, "TYER")), "");
            //    Mediafile.TrackNumber = GetStringForNullOrEmptyProperty((await LibVM.GetTextFrame(Data, "TRCK")), "");
            //    Mediafile.OrginalFilename = file.DisplayName;
            //    //Mediafile.Date = DateTime.Now.Date.ToString("dd/MM/yyyy");
            //    //if (Mediafile.Genre != null && Mediafile.Genre != "NaN")
            //    //{
            //    //    LibVM.GenreCollection.Add(Mediafile.Genre);
            //    //}
            //    if (Data.AttachedPictureFrames.Count > 0)
            //    {
            //        var albumartFolder = ApplicationData.Current.LocalFolder;
            //        LibVM.SaveImages(Data, Mediafile);
            //        Mediafile.AttachedPicture = albumartFolder.Path + @"\AlbumArts\" + (Mediafile.Album + Mediafile.LeadArtist).ToLower().ToSha1() + ".jpg";
            //    }
            //}
            Mediafile.Path            = file.Path;
            Mediafile.OrginalFilename = file.DisplayName;
            Mediafile.State           = PlayerState.Stopped;
            var properties = await file.Properties.GetMusicPropertiesAsync();

            Mediafile.Title       = GetStringForNullOrEmptyProperty(properties.Title, System.IO.Path.GetFileNameWithoutExtension(file.Path));
            Mediafile.Album       = GetStringForNullOrEmptyProperty(properties.Album, "Unknown Album");
            Mediafile.LeadArtist  = GetStringForNullOrEmptyProperty(properties.Artist, "Unknown Artist");
            Mediafile.Genre       = string.Join(",", properties.Genre);
            Mediafile.Year        = properties.Year.ToString();
            Mediafile.TrackNumber = properties.TrackNumber.ToString();
            Mediafile.Length      = GetStringForNullOrEmptyProperty(properties.Duration.ToString(@"mm\:ss"), "00:00");
            //var x = await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.MusicView, 1000, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);
            //StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 300);
            //    if (thumbnail != null && thumbnail.Type == ThumbnailType.Image)
            //    {
            //        var albumartFolder = ApplicationData.Current.LocalFolder;
            //        LibVM.SaveImages(thumbnail, Mediafile);
            //        Mediafile.AttachedPicture = albumartFolder.Path + @"\AlbumArts\" + (Mediafile.Album + Mediafile.LeadArtist).ToLower().ToSha1() + ".jpg";
            //    }

            return(Mediafile);
        }
 void PlayFile(Mediafile toPlayFile, bool play = false)
 {
     if (Player.PlayerState == PlayerState.Paused || Player.PlayerState == PlayerState.Stopped)
     {
         Load(toPlayFile);
     }
     else
     {
         LibVM.PlayCommand.Execute(toPlayFile);
     }
 }
Beispiel #7
0
 public static bool RemoveMediafile(Mediafile file)
 {
     if (file != null)
     {
         LibVM.TracksCollection.Elements.Remove(file);
         LibVM.Database.Remove(file);
         LibVM.SongCount--;
         return(true);
     }
     return(false);
 }
Beispiel #8
0
 public static bool AddMediafile(Mediafile file, int index = -1)
 {
     if (file != null)
     {
         LibVM.TracksCollection.Elements.Insert(index == -1 ? LibVM.TracksCollection.Elements.Count: index, file);
         LibVM.Database.Insert(file);
         LibVM.SongCount++;
         return(true);
     }
     return(false);
 }
Beispiel #9
0
        public async Task <Mediafile> GetUpcomingSong(bool isNext = false)
        {
            var playingCollection = GetPlayingCollection();

            NowPlayingQueue = playingCollection;
            if (playingCollection != null && playingCollection.Any())
            {
                try
                {
                    int indexOfCurrentlyPlayingFile = -1;
                    if (playingCollection.Any(t => t.State == PlayerState.Playing))
                    {
                        indexOfCurrentlyPlayingFile = playingCollection.IndexOf(playingCollection.FirstOrDefault(t => t.State == PlayerState.Playing));
                    }

                    Mediafile toPlayFile = null;
                    if (Shuffle)
                    {
                        //only recreate the shuffled list if the current list is null or
                        //if it has gotten stale.
                        if (_shuffledList.Count < playingCollection.Count || _shuffledList == null)
                        {
                            _shuffledList = await ShuffledCollection();
                        }

                        //just set the index of currently playing file to -1
                        //if we are reached the last file in the playing collection.
                        if (indexOfCurrentlyPlayingFile > playingCollection.Count - 2)
                        {
                            indexOfCurrentlyPlayingFile = -1;
                        }
                        toPlayFile = _shuffledList?.ElementAt(indexOfCurrentlyPlayingFile + 1);
                    }
                    else if (IsSourceGrouped)
                    {
                        toPlayFile = GetNextSongInGroup();
                    }
                    else
                    {
                        toPlayFile = indexOfCurrentlyPlayingFile <= playingCollection.Count - 2 && indexOfCurrentlyPlayingFile != -1 ? playingCollection.ElementAt(indexOfCurrentlyPlayingFile + 1) : Repeat == "Repeat List" || isNext?playingCollection.ElementAt(0) : null;
                    }
                    return(toPlayFile);
                }
                catch (Exception ex)
                {
                    BLogger.Logger.Error("An error occured while trying to play next song.", ex);
                    await NotificationManager.ShowMessageAsync("An error occured while trying to play next song. Trying again...");

                    ClearPlayerState();
                    PlayNext();
                }
            }
            return(null);
        }
 void PlayFile(Mediafile toPlayFile, bool play = false)
 {
     if (Player.PlayerState == PlayerState.Paused || Player.PlayerState == PlayerState.Stopped)
     {
         Load(toPlayFile);
     }
     else
     {
         Messenger.Instance.NotifyColleagues(MessageTypes.MSG_PLAY_SONG, toPlayFile);
     }
 }
Beispiel #11
0
        /// <summary>
        /// Create mediafile from StorageFile.
        /// </summary>
        /// <param name="file">the storage file</param>
        /// <param name="cache">cache into the system for future access?</param>
        /// <returns>The created mediafile</returns>
        public static async Task <Mediafile> CreateMediafile(StorageFile file, bool cache = false)
        {
            try
            {
                if (cache)
                {
                    StorageApplicationPermissions.FutureAccessList.Add(file);
                }

                var properties = await file.Properties.GetMusicPropertiesAsync();

                var extraProperties = await file.Properties.RetrievePropertiesAsync(GetExtraPropertiesNames());

                if (extraProperties.TryGetValue("System.DRM.IsProtected", out object drm))
                {
                    if ((bool)drm)
                    {
                        throw new InvalidDataException("File is DRM Protected.");
                    }
                }
                var mediafile = new Mediafile()
                {
                    Path            = file.Path,
                    OrginalFilename = file.DisplayName,
                    Title           = properties.Title.GetStringForNullOrEmptyProperty(Path.GetFileNameWithoutExtension(file.Path)),
                    Album           = properties.Album.GetStringForNullOrEmptyProperty("Unknown Album"),
                    LeadArtist      = properties.Artist.GetStringForNullOrEmptyProperty("Unknown Artist"),
                    Genre           = string.Join(",", properties.Genre),
                    Year            = properties.Year.ToString(),
                    TrackNumber     = properties.TrackNumber.ToString(),
                    Length          = new DoubleToTimeConverter().Convert(properties.Duration.TotalSeconds, typeof(double), null, "").ToString(),
                    AddedDate       = DateTime.Now
                };

                var albumartFolder   = ApplicationData.Current.LocalFolder;
                var albumartLocation = albumartFolder.Path + @"\AlbumArts\" + (mediafile.Album + mediafile.LeadArtist).ToLower().ToSha1() + ".jpg";

                if (System.IO.File.Exists(albumartLocation))
                {
                    mediafile.AttachedPicture = albumartLocation;
                }
                return(mediafile);
            }
            catch (InvalidDataException)
            {
                return(null);
            }
            catch (Exception ex)
            {
                await SharedLogic.NotificationManager.ShowMessageAsync(ex.Message + "||" + file.Path);

                return(null);
            }
        }
Beispiel #12
0
        public async Task <string> FetchLyrics(Mediafile mediaFile)
        {
            var results = await Search(WebUtility.UrlEncode(mediaFile.Title + " " + mediaFile.LeadArtist)).ConfigureAwait(false);

            if (results.Result.SongInfo?.SongList?.Any() == true)
            {
                var bSong = results.Result.SongInfo.SongList.First(t => t.Title.Contains(mediaFile.Title));
                return((await RequestSongLrc(bSong.SongId).ConfigureAwait(false)).LrcContent);
            }
            return("");
        }
        public async void Load(Mediafile mp3file, bool play = false, double currentPos = 0, double vol = 50)
        {
            if (mp3file != null)
            {
                try
                {
                    if (play == true)
                    {
                        Player.IgnoreErrors = true;
                    }

                    if (await Player.Load(mp3file))
                    {
                        TracksCollection?.Elements.Where(t => t.State == PlayerState.Playing).ToList().ForEach(new Action <Mediafile>((Mediafile file) => { file.State = PlayerState.Stopped; service.UpdateMediafile(file); }));
                        PlaylistSongCollection?.Where(t => t.State == PlayerState.Playing).ToList().ForEach(new Action <Mediafile>((Mediafile file) => { file.State = PlayerState.Stopped; }));
                        PlayPauseCommand.IsEnabled = true;
                        mp3file.State = PlayerState.Playing;
                        if (Player.Volume == 50)
                        {
                            Player.Volume = vol;
                        }
                        if (play)
                        {
                            PlayPauseCommand.Execute(null);
                        }
                        else
                        {
                            DontUpdatePosition = true;
                            CurrentPosition    = currentPos;
                        }
                        if (GetPlayingCollection() != null)
                        {
                            UpcomingSong = await GetUpcomingSong();
                        }

                        Themes.ThemeManager.SetThemeColor(Player.CurrentlyPlayingFile.AttachedPicture);
                    }
                    else
                    {
                        BLogger.Logger.Error("Failed to load file. Loading next file...");
                        TracksCollection?.Elements.Where(t => t.State == PlayerState.Playing).ToList().ForEach(new Action <Mediafile>((Mediafile file) => { file.State = PlayerState.Stopped; service.UpdateMediafile(file); }));
                        PlaylistSongCollection?.Where(t => t.State == PlayerState.Playing).ToList().ForEach(new Action <Mediafile>((Mediafile file) => { file.State = PlayerState.Stopped; }));
                        mp3file.State = PlayerState.Playing;
                        int indexoferrorfile = GetPlayingCollection().IndexOf(GetPlayingCollection().FirstOrDefault(t => t.Path == mp3file.Path));
                        Player.IgnoreErrors = false;
                        Load(await GetUpcomingSong(), true);
                    }
                }
                catch (Exception ex)
                {
                    BLogger.Logger.Error("Failed to load file.", ex);
                }
            }
        }
 public void Dispose()
 {
     PlaylistSongCollection?.Clear();
     TracksCollection?.Clear();
     DontUpdatePosition = true;
     CurrentPosition    = 0;
     UpcomingSong       = null;
     timer.Stop();
     ShuffledList?.Clear();
     PlayPauseIcon = new SymbolIcon(Symbol.Play);
 }
Beispiel #15
0
 async void PlayFile(Mediafile toPlayFile)
 {
     if (player.PlayerState == PlayerState.Paused || player.PlayerState == PlayerState.Stopped)
     {
         Load(await StorageFile.GetFileFromPathAsync(toPlayFile.Path));
     }
     else
     {
         LibVM.PlayCommand.Execute(toPlayFile);
     }
 }
Beispiel #16
0
 public async void Play(StorageFile para, Mediafile mp3File = null, double currentPos = 0, bool play = true, double vol = 50)
 {
     if (para != null)
     {
         mp3File = await CreateMediafile(para, true);
     }
     else if (para == null && mp3File == null)
     {
         return;
     }
     Load(mp3File, play, currentPos, vol);
 }
Beispiel #17
0
        public async Task <string> FetchLyrics(Mediafile mediaFile)
        {
            var results = await SearchSongs(WebUtility.UrlEncode(mediaFile.Title + " " + mediaFile.LeadArtist)).ConfigureAwait(false);

            var bSong = results.Result.Songs.FirstOrDefault(t => t.Name.ToLower().Contains(mediaFile.Title.ToLower()));

            if (bSong != null)
            {
                return((await GetLyrics(bSong.Id.ToString()).ConfigureAwait(false)).Lrc.Lyric);
            }
            return(null);
        }
Beispiel #18
0
        /// <summary>
        /// Add folder to Library asynchronously.
        /// </summary>
        /// <param name="queryResult">The query result after querying in a specific folder.</param>
        /// <returns></returns>
        public static async Task <IEnumerable <Mediafile> > GetSongsFromFolderAsync(StorageFolder folder, bool useIndexer = true)
        {
            StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(DirectoryWalker.GetQueryOptions(null, useIndexer));

            uint index = 0, stepSize = 20;
            IReadOnlyList <StorageFile> files = await queryResult.GetFilesAsync(index, stepSize);

            index += stepSize;

            var count = await queryResult.GetItemCountAsync();

            if (count <= 0)
            {
                await SharedLogic.Instance.NotificationManager.ShowMessageAsync("No songs found! Please try again.");

                return(null);
            }
            var   tempList = new List <Mediafile>((int)count);
            short progress = 0;

            try
            {
                // Note that I'm paging in the files as described
                while (files.Count != 0)
                {
                    var fileTask = queryResult.GetFilesAsync(index, stepSize).AsTask();
                    for (int i = 0; i < files.Count; i++)
                    {
                        progress++;
                        Messenger.Instance.NotifyColleagues(MessageTypes.MsgUpdateSongCount, progress);
                        Mediafile mp3File = await TagReaderHelper.CreateMediafile(files[i], false).ConfigureAwait(false); //the core of the whole method.

                        if (mp3File != null)
                        {
                            mp3File.FolderPath = Path.GetDirectoryName(files[i].Path);
                            await SaveSingleFileAlbumArtAsync(mp3File, files[i]).ConfigureAwait(false);

                            await SharedLogic.Instance.NotificationManager.ShowMessageAsync(progress + "\\" + count + " Song(s) Loaded", 0);

                            tempList.Add(mp3File);
                        }
                    }
                    files  = await fileTask;
                    index += stepSize;
                }
            }
            catch (Exception ex)
            {
                string message1 = ex.Message + "||" + ex.InnerException;
                await SharedLogic.Instance.NotificationManager.ShowMessageAsync(message1);
            }
            return(tempList.DistinctBy(f => f.OrginalFilename));
        }
Beispiel #19
0
        public async Task <Mediafile> GetUpcomingSong(bool isNext = false)
        {
            var playingCollection = GetPlayingCollection();

            NowPlayingQueue = playingCollection;
            if (playingCollection != null)
            {
                try
                {
                    Mediafile toPlayFile = null;
                    if (Shuffle)
                    {
                        //only recreate the shuffled list if the current list is null or
                        //if it has gotten stale.
                        if (_shuffledList.Count < playingCollection.Count || _shuffledList == null)
                        {
                            _shuffledList = await ShuffledCollection();
                        }

                        //just set the index of currently playing file to -1
                        //if we are reached the last file in the playing collection.
                        if (_indexOfCurrentlyPlayingFile > playingCollection.Count - 2)
                        {
                            _indexOfCurrentlyPlayingFile = -1;
                        }
                        toPlayFile = _shuffledList?.ElementAt(_indexOfCurrentlyPlayingFile + 1);
                    }
                    else if (IsSourceGrouped)
                    {
                        toPlayFile = GetNextOrPrevSongInGroup(false) ?? throw new NullReferenceException("Cannot get next song in group.");
                    }
                    else
                    {
                        toPlayFile = _indexOfCurrentlyPlayingFile <= playingCollection.Count - 2 && _indexOfCurrentlyPlayingFile != -1
                                    ? playingCollection.ElementAt(_indexOfCurrentlyPlayingFile + 1)
                                    : Repeat == "Repeat List" || isNext
                                    ? playingCollection.ElementAt(0)
                                    : null;
                    }
                    return(toPlayFile);
                }
                catch (Exception ex)
                {
                    BLogger.E("An error occured while trying to play next song.", ex);
                    await SharedLogic.Instance.NotificationManager.ShowMessageAsync("An error occured while trying to play next song. Trying again...");

                    ClearPlayerState();
                    PlayNext();
                }
            }
            return(null);
        }
Beispiel #20
0
        public async Task <IActionResult> Media(string mediaId)
        {
            var       currentTeacherId = Request.Cookies["teacher"];
            Mediafile mediafile        = await firestoreProvider.GetMediafileByIdAsync(mediaId);

            if (mediafile.TeacherId == currentTeacherId)
            {
                ViewBag.editLink = true;
            }
            ViewBag.mediafile  = mediafile;
            ViewBag.bucketName = storageProvider.bucketName;
            return(View());
        }
Beispiel #21
0
        public async Task <Mediafile> GetMediafileByIdAsync(string mediafileId)
        {
            Mediafile mdf = null;

            var docRef  = db.Collection("mediafiles").Document(mediafileId);
            var mdfSnap = await docRef.GetSnapshotAsync();

            if (mdfSnap.Exists)
            {
                mdf = mdfSnap.ConvertTo <Mediafile>();
            }

            return(mdf);
        }
Beispiel #22
0
 public static bool AddMediafile(Mediafile file, int index = -1)
 {
     if (file != null)
     {
         if (service == null)
         {
             service = new LibraryService(new DatabaseService());
         }
         SettingsViewModel.TracksCollection.Elements.Insert(index == -1 ? SettingsViewModel.TracksCollection.Elements.Count: index, file);
         service.AddMediafile(file);
         return(true);
     }
     return(false);
 }
Beispiel #23
0
 public static bool RemoveMediafile(Mediafile file)
 {
     if (file != null)
     {
         if (service == null)
         {
             service = new LibraryService(new DatabaseService());
         }
         SettingsViewModel.TracksCollection.Elements.Remove(file);
         service.RemoveMediafile(file);
         return(true);
     }
     return(false);
 }
        /// <summary>
        /// Plays the selected file. <seealso cref="PlayCommand"/>
        /// </summary>
        /// <param name="path"><see cref="BreadPlayer.Models.Mediafile"/> to play.</param>
        public async void Play(object path)
        {
            Mediafile mediaFile = null;

            if (path is Mediafile)
            {
                mediaFile             = path as Mediafile;
                isPlayingFromPlaylist = false;
            }
            else if (path is ThreadSafeObservableCollection <Mediafile> )
            {
                mediaFile = (path as ThreadSafeObservableCollection <Mediafile>)[0];
                Messenger.Instance.NotifyColleagues(MessageTypes.MSG_LIBRARY_LOADED, path as ThreadSafeObservableCollection <Mediafile>);
                isPlayingFromPlaylist = true;
            }
            else if (path is Playlist)
            {
                using (Service.PlaylistService service = new Service.PlaylistService((path as Playlist).Name, (path as Playlist).IsPrivate, (path as Playlist).Password))
                {
                    if (service.IsValid)
                    {
                        var songList = new ThreadSafeObservableCollection <Mediafile>(await service.GetTracks().ConfigureAwait(false));
                        mediaFile = songList[0];
                        Messenger.Instance.NotifyColleagues(MessageTypes.MSG_LIBRARY_LOADED, songList);
                        isPlayingFromPlaylist = true;
                    }
                }
            }
            else
            {
                return;
            }

            AddToRecentCollection(mediaFile);
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                Messenger.Instance.NotifyColleagues(MessageTypes.MSG_PLAY_SONG, new List <object>()
                {
                    mediaFile, true, isPlayingFromPlaylist
                });
                (PlayCommand as RelayCommand).IsEnabled = false;
                await Task.Delay(100);
                (PlayCommand as RelayCommand).IsEnabled = true;

                if (TracksCollection.Elements.FirstOrDefault(t => t.Path == Player?.CurrentlyPlayingFile?.Path) != null)
                {
                    TracksCollection.Elements.FirstOrDefault(t => t.Path == Player?.CurrentlyPlayingFile?.Path).State = PlayerState.Playing;
                }
            });
        }
Beispiel #25
0
        public static async Task <string> FetchLyrics(Mediafile file, string lyricSource)
        {
            try
            {
                var mediaFile = new Mediafile();
                mediaFile.Title = TagParser.ParseTitle(file.Title.ToString());
                var           cleanedArtist = TagParser.ParseTitle(file.LeadArtist.ToString());
                List <string> parsedArtists = TagParser.ParseArtists(cleanedArtist);
                if (string.IsNullOrEmpty(cleanedArtist))
                {
                    cleanedArtist = file.Title;
                    parsedArtists = TagParser.ParseArtists(cleanedArtist);
                    parsedArtists.RemoveAt(0);
                }
                mediaFile.LeadArtist = !parsedArtists.Any() ? file.LeadArtist : TagParser.ParseTitle(parsedArtists[0]);
                string Lyrics = "";
                switch (lyricSource)
                {
                case "Auto":
                    for (int i = 0; i < Sources.Length; i++)
                    {
                        var lrc = await Sources[i].FetchLyrics(mediaFile).ConfigureAwait(false);
                        if (LrcParser.IsLrc(lrc))
                        {
                            Lyrics = lrc;
                            break;
                        }
                    }
                    break;

                case "Netease":
                    Lyrics = await Sources[0].FetchLyrics(mediaFile).ConfigureAwait(false);
                    break;

                case "Baidu":
                    Lyrics = await Sources[2].FetchLyrics(mediaFile).ConfigureAwait(false);
                    break;

                case "Xiami":
                    Lyrics = await Sources[1].FetchLyrics(mediaFile).ConfigureAwait(false);
                    break;
                }
                return(Lyrics);
            }
            catch
            {
                return(null);
            }
        }
        public static async Task ChangeLockscreenImage(Mediafile mediaFile)
        {
            if (!string.IsNullOrEmpty(mediaFile.AttachedPicture))
            {
                await SaveCurrentLockscreenImage();

                var albumart = await StorageFile.GetFileFromPathAsync(mediaFile.AttachedPicture);

                await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(albumart);
            }
            else
            {
                await ResetLockscreenImage();
            }
        }
 private void AddToRecentCollection(Mediafile mediaFile)
 {
     LibraryService   = new LibraryService(new DatabaseService());
     RecentCollection = LibraryService.GetRecentCollection();
     if (RecentlyPlayedCollection.Any(t => t.Path == mediaFile.Path))
     {
         RecentlyPlayedCollection.Remove(RecentlyPlayedCollection.First(t => t.Path == mediaFile.Path));
     }
     if (RecentCollection.Exists(t => t.Path == mediaFile.Path))
     {
         RecentCollection.Delete(t => t.Path == mediaFile.Path);
     }
     RecentlyPlayedCollection.Add(mediaFile);
     RecentCollection.Insert(mediaFile);
 }
Beispiel #28
0
 public async Task<string> FetchLyrics(Mediafile mediaFile)
 {
     using (HttpClient client = new HttpClient())
     {
         var results = await SearchAsync(WebUtility.UrlEncode(mediaFile.Title + " " + mediaFile.LeadArtist));
         var xResult = results.Data.Songs.First(t => t.SongName.ToLower().Contains(mediaFile.Title.ToLower()));
         var xSong = await GetSongDetailAsync(xResult.SongId.ToString());
         if (xSong.Data.TrackList?.Any() == true && !string.IsNullOrEmpty(xSong.Data.TrackList[0].LyricUrl))
             return await client.GetStringAsync(xSong.Data.TrackList[0].LyricUrl).ConfigureAwait(false);
         else if (!string.IsNullOrEmpty(xResult.Lyric) && xSong.Data.TrackList == null)
             return await client.GetStringAsync(xResult.Lyric).ConfigureAwait(false);
         else
             return "";
     }
 }
Beispiel #29
0
        public async Task <Mediafile> GetUpcomingSong(bool isNext = false)
        {
            var playingCollection = GetPlayingCollection();

            NowPlayingQueue = playingCollection;
            if (playingCollection != null && playingCollection.Any())
            {
                try
                {
                    int indexOfCurrentlyPlayingFile = -1;
                    if (playingCollection.Any(t => t.State == PlayerState.Playing))
                    {
                        indexOfCurrentlyPlayingFile = playingCollection.IndexOf(playingCollection.FirstOrDefault(t => t.State == PlayerState.Playing));
                    }

                    Mediafile toPlayFile = null;
                    if (Shuffle)
                    {
                        if (_shuffledList.Count < playingCollection.Count || _shuffledList == null)
                        {
                            _shuffledList = await ShuffledCollection();

                            indexOfCurrentlyPlayingFile = 0;
                        }
                        toPlayFile = _shuffledList?.ElementAt(indexOfCurrentlyPlayingFile + 1);
                    }
                    else if (IsSourceGrouped)
                    {
                        toPlayFile = GetNextSongInGroup();
                    }
                    else
                    {
                        toPlayFile = indexOfCurrentlyPlayingFile <= playingCollection.Count - 2 && indexOfCurrentlyPlayingFile != -1 ? playingCollection.ElementAt(indexOfCurrentlyPlayingFile + 1) : Repeat == "Repeat List" || isNext?playingCollection.ElementAt(0) : null;
                    }
                    return(toPlayFile);
                }
                catch (Exception ex)
                {
                    BLogger.Logger.Error("An error occured while trying to play next song.", ex);
                    await NotificationManager.ShowMessageAsync("An error occured while trying to play next song. Trying again...");

                    TracksCollection?.Elements.Where(t => t.State == PlayerState.Playing).ToList().ForEach(file => { file.State = PlayerState.Stopped; });
                    PlaylistSongCollection?.Where(t => t.State == PlayerState.Playing).ToList().ForEach(file => { file.State = PlayerState.Stopped; });
                    PlayNext();
                }
            }
            return(null);
        }
Beispiel #30
0
        /// <summary>
        /// Loads the specified file into the player.
        /// </summary>
        /// <param name="fileName">Path to the music file.</param>
        /// <returns>Boolean</returns>
        public async Task <bool> Load(Mediafile mp3file)
        {
            if (mp3file != null && mp3file.Length != "00:00")
            {
                try
                {
                    string sPath = mp3file.Path;
                    await Stop();

                    await Task.Run(() =>
                    {
                        Bass.Stop();
                        Bass.Start();

                        handle      = ManagedBass.Bass.CreateStream(sPath, 0, 0, BassFlags.AutoFree);
                        PlayerState = PlayerState.Stopped;
                        Length      = Bass.ChannelBytes2Seconds(handle, Bass.ChannelGetLength(handle));
                        InitializeExtensions(sPath);
                        MediaStateChanged(this, new MediaStateChangedEventArgs(PlayerState.Stopped));
                        Bass.ChannelSetSync(handle, SyncFlags.End | SyncFlags.Mixtime, 0, _sync);
                        CurrentlyPlayingFile = mp3file;
                        CoreWindowLogic.UpdateSmtc();
                        CoreWindowLogic.Stringify();

                        //
                    });

                    return(true);
                }
                catch (Exception ex)
                {
                    await NotificationManager.ShowAsync(ex.Message + "||" + mp3file.OrginalFilename);
                }
            }
            else
            {
                string error = "The file " + mp3file.OrginalFilename + " is either corrupt, incomplete or unavailable. \r\n\r\n Exception details: No data available.";
                if (IgnoreErrors == false)
                {
                    CoreWindowLogic.ShowMessage(error, "File corrupt");
                }
                else
                {
                    await NotificationManager.ShowAsync(error);
                }
            }
            return(false);
        }