示例#1
0
文件: Lastfm.cs 项目: sagar-sm/Mu3
        public static async void track_updateNowPlaying(MusicProperties id3)
        {
            //try
            //{
            string updtrack_sig = "album" + id3.Album + "api_key" + Globalv.lfm_api_key + "artist" + id3.Artist + "methodtrack.updateNowPlaying" + "sk" + Globalv.session_key + "track" + id3.Title + "0e6e780c3cfa3faedf0c58d5aa6de92f";

            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm("MD5");
            CryptographicHash     objHash    = objAlgProv.CreateHash();
            IBuffer buffSig = CryptographicBuffer.ConvertStringToBinary(updtrack_sig, BinaryStringEncoding.Utf8);

            objHash.Append(buffSig);
            IBuffer buffSighash = objHash.GetValueAndReset();

            updtrack_sig = CryptographicBuffer.EncodeToHexString(buffSighash);

            HttpClient cli = new HttpClient();

            cli.DefaultRequestHeaders.ExpectContinue = false;     //important
            string track_updateNowPlaying = @"method=track.updateNowPlaying&track=" + id3.Title + @"&artist=" + id3.Artist + @"&album=" + id3.Album + @"&api_key=" + Globalv.lfm_api_key + @"&api_sig=" + updtrack_sig + @"&sk=" + Globalv.session_key;

            cli.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
            HttpContent tunp = new StringContent(track_updateNowPlaying);

            tunp.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            var upd_now_playing = await cli.PostAsync(new Uri("http://ws.audioscrobbler.com/2.0", UriKind.Absolute), tunp);

            //}
            // catch (Exception) { };
        }
        async void GetMusicInfoAsync(StorageFile file)
        {
            MusicProperties musicProps = await file.Properties.GetMusicPropertiesAsync();

            Title  = musicProps.Title;
            Artist = musicProps.Artist;
        }
示例#3
0
        public async void AddToAlbum(StorageFile file)
        {
            MusicProperties fp = await file.Properties.GetMusicPropertiesAsync();

            //check if album already exists
            bool addedToAlbum = false;

            //find album and add song to it
            foreach (Album album in Albums)
            {
                if (album.Name.Equals(fp.Album))
                {
                    album.AddSong(fp, this, file);
                    addedToAlbum = true;
                }
            }
            // if song was not added to album create new album and add song
            if (!addedToAlbum)
            {
                Albums.Add(new Album {
                    artist = this, Name = fp.Album
                });
                Albums[Albums.Count - 1].AddSong(fp, this, file);
            }
        }
        private async Task <List <StorageFile> > PickRandomSonds(ObservableCollection <StorageFile> allSonds)
        {
            Random random      = new Random();
            var    songCount   = allSonds.Count();
            var    randomSongs = new List <StorageFile>();

            while (randomSongs.Count < 10)
            {
                var             randomNumber = random.Next(songCount);
                var             randomSong   = allSonds[randomNumber];
                MusicProperties randomSongMusicProperties = await randomSong.Properties.GetMusicPropertiesAsync();

                bool isDuplicate = false;
                foreach (var song in randomSongs)
                {
                    MusicProperties songMusicProperties = await song.Properties.GetMusicPropertiesAsync();

                    if (String.IsNullOrEmpty(randomSongMusicProperties.Album) || randomSongMusicProperties.Album == songMusicProperties.Album)
                    {
                        isDuplicate = true;
                    }
                }
                if (!isDuplicate)
                {
                    randomSongs.Add(randomSong);
                }
            }
            return(randomSongs);
        }
示例#5
0
        private async Task <List <StorageFile> > GetRandomSong(ObservableCollection <StorageFile> allsongs)
        {
            Random rd             = new Random();
            var    allsongs_count = allsongs.Count();

            random_songs = new List <StorageFile>();
            while (random_songs.Count() < 10)
            {
                var index       = rd.Next(allsongs_count);
                var random_song = allsongs[index];
                IsAddSong = false;
                MusicProperties set_randomsong = await random_song.Properties.GetMusicPropertiesAsync();

                foreach (var song in random_songs)
                {
                    MusicProperties get_randomsong = await song.Properties.GetMusicPropertiesAsync();

                    if (String.IsNullOrEmpty(set_randomsong.Album) || set_randomsong.Album == get_randomsong.Album)
                    {
                        IsAddSong = true;
                    }
                }
                if (IsAddSong == false)
                {
                    random_songs.Add(random_song);
                }
            }
            return(random_songs);
        }
示例#6
0
 public StorageAudio(StorageFile file, MusicProperties props)
     : base(file, null)
 {
     Title     = props.Title;
     Performer = props.AlbumArtist;
     Duration  = (int)props.Duration.TotalSeconds;
 }
示例#7
0
 protected Track CreateTrack(MusicProperties musicProps, Tag tag, string audioUrl)
 {
     return(new Track
     {
         Title = CleanText(tag.Title),
         AlbumTitle = CleanText(tag.Album),
         AlbumArtist = CleanText(tag.FirstAlbumArtist) ?? CleanText(tag.FirstPerformer),
         Artists = CleanText(tag.JoinedPerformers),
         DisplayArtist = CleanText(tag.FirstPerformer),
         Bitrate = (int)musicProps.Bitrate,
         Duration = musicProps.Duration,
         Genres = tag.JoinedGenres,
         Publisher = musicProps.Publisher,
         Lyrics = tag.Lyrics,
         Comment = tag.Comment,
         Conductors = tag.Conductor,
         Composers = tag.JoinedComposers,
         TrackNumber = tag.Track,
         TrackCount = tag.TrackCount,
         DiscCount = tag.DiscCount,
         DiscNumber = tag.Disc,
         Year = tag.Year,
         LikeState = musicProps.Rating > 0 ? LikeState.Like : LikeState.None,
         AudioLocalUri = audioUrl,
         Type = TrackType.Local
     });
 }
示例#8
0
        async private void Button_Click(object sender, RoutedEventArgs e)
        {
            //MediaPlayer lib = new MediaPlayer();

            var folder = Windows.Storage.KnownFolders.MusicLibrary;
            var files  = await folder.GetFilesAsync();

            StorageFolder musicFolder            = KnownFolders.MusicLibrary;
            IReadOnlyList <StorageFile> fileList = await musicFolder.GetFilesAsync();

            foreach (var file in fileList)
            {
                MusicProperties musicProperties = await file.Properties.GetMusicPropertiesAsync();

                Debug.WriteLine("url: " + file.Path);
                Debug.WriteLine("Name: " + file.Name);
                Debug.WriteLine("Name: " + file.Name);
                Debug.WriteLine("Album: " + musicProperties.Album);
                Debug.WriteLine("Rating: " + musicProperties.Rating);
                Debug.WriteLine("Producers: " + musicProperties.Publisher);
            }

            //var files = await folder.GetFilesAsync();
            //Debug.WriteLine("aye");
            //foreach (var test in folder)
            //{
            //   Debug.WriteLine(test.DisplayName);
            //}
        }
示例#9
0
        public async Task <TrackItem> GetTrackItemFromFile(StorageFile track, string token = null)
        {
            //TODO: Warning, is it safe to consider this a good idea?
            var trackItem = musicDatabase.LoadTrackFromPath(track.Path);

            if (trackItem != null)
            {
                return(trackItem);
            }

            MusicProperties trackInfos = null;

            try
            {
                trackInfos = await track.Properties.GetMusicPropertiesAsync();
            }
            catch
            {
            }
            trackItem = new TrackItem
            {
                ArtistName = (string.IsNullOrEmpty(trackInfos?.Artist)) ? Strings.UnknownArtist : trackInfos?.Artist,
                AlbumName  = trackInfos?.Album ?? Strings.UnknownAlbum,
                Name       = (string.IsNullOrEmpty(trackInfos?.Title)) ? track.DisplayName : trackInfos?.Title,
                Path       = track.Path,
                Duration   = trackInfos?.Duration ?? TimeSpan.Zero,
                File       = track,
            };
            if (!string.IsNullOrEmpty(token))
            {
                trackItem.Token = token;
            }
            return(trackItem);
        }
        private async Task displaysongs(ObservableCollection <StorageFile> dispsongs)
        {
            foreach (var file in dispsongs)
            {
                MusicProperties property = await file.Properties.GetMusicPropertiesAsync();

                StorageItemThumbnail thumb = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 230, ThumbnailOptions.ResizeThumbnail);

                var name       = file.Name;
                var countt     = dispsongs.Count();
                var coverimage = new BitmapImage();
                coverimage.SetSource(thumb);

                totalsongsno.Text = string.Format("Total Songs: {0}", countt);
                var song = new Songprop();
                song.ID = id;

                song.songname   = name;
                song.songtitle  = property.Title;
                song.songartist = property.Artist;
                song.songalbum  = property.Album;
                song.albumcover = coverimage;
                song.songfile   = file;
                Songs.Add(song);
                id++;
            }
        }
示例#11
0
        private async void dataGrid_Drop(object sender, DragEventArgs e)
        {
            if (e.DataView.Contains(StandardDataFormats.StorageItems))
            {
                var items = await e.DataView.GetStorageItemsAsync();

                if (items.Any())
                {
                    StorageFolder folder = ApplicationData.Current.LocalFolder;

                    for (int i = 0; i < items.Count; i++)
                    {
                        var         storageFile = items[i] as StorageFile;
                        var         contentType = storageFile.ContentType;
                        StorageFile newFile     = await storageFile.CopyAsync(folder, storageFile.Name, NameCollisionOption.GenerateUniqueName);

                        MusicProperties metaData = await newFile.Properties.GetMusicPropertiesAsync();

                        playlistTracks.Add(newFile);
                        playlistsongsMetaData.Add(new Song(metaData.Title, metaData.Artist, metaData.Album, AudioFileRetriever.FormatTrackDuration(metaData.Duration.TotalMinutes), metaData.Genre.Count == 0 ? "" : metaData.Genre[0], newFile.Path));
                    }
                    dataGrid.ItemsSource = null;
                    dataGrid.Columns.Clear();
                    dataGrid.ItemsSource = playlistsongsMetaData;
                }
            }
        }
        /// <summary>
        /// Helper method which updates the UI to show a new list of 10 random songs
        /// </summary>
        /// <param name="files">The list of files which we want to display</param>
        private async Task PopulateSongListAsync(List <StorageFile> files)
        {
            //Clear the list of songs for old selection
            Songs.Clear();

            int id = 0;

            foreach (var file in files)
            {
                MusicProperties songProperties = await file.Properties.GetMusicPropertiesAsync();

                //The next three lines grabs the thumbnail for the selected item
                StorageItemThumbnail currentThumbnail = await file.GetThumbnailAsync(
                    ThumbnailMode.MusicView,
                    200,
                    ThumbnailOptions.UseCurrentScale);

                var albumCover = new BitmapImage();
                albumCover.SetSource(currentThumbnail);

                //Make a song object
                var song = new Song();

                song.Id         = id++;
                song.Title      = songProperties.Title;
                song.Album      = songProperties.Album;
                song.Artist     = songProperties.Artist;
                song.AlbumCover = albumCover;
                song.SongFile   = file;
                song.Selected   = false;

                Songs.Add(song);
            }
        }
示例#13
0
        public async void AddVideo(StorageFile file)
        {
            if (file == null)
            {
                return;
            }

            MusicProperties musicProperties = await file.Properties.GetMusicPropertiesAsync();

            MusicPiece song = new MusicPiece()
            {
                Title      = file.Name,
                Artist     = "",
                AlbumCover = new BitmapImage(),
                isMusic    = false
            };

            song.file = file;

            song.AlbumCover.UriSource = new Uri("ms-appx:///Assets/LockScreenLogo.scale-200.png");
            musics.Add(song);

            var mediaSource = MediaSource.CreateFromStorageFile(file);
            var item        = new MediaPlaybackItem(mediaSource);

            item.CanSkip = true;
            playbackList.Items.Add(item);
        }
示例#14
0
文件: Lastfm.cs 项目: sagar-sm/Mu3
        public static async Task <string> track_love(MusicProperties id3)
        {
            try
            {
                string scrb_track_sig = "api_key" + Globalv.lfm_api_key + "artist" + id3.Artist + "methodtrack.love" + "sk" + Globalv.session_key + "track" + id3.Title + "0e6e780c3cfa3faedf0c58d5aa6de92f";

                //UTF8Encoding utf8e = new System.Text.UTF8Encoding();
                //scrb_track_sig = utf8e.GetString(utf8e.GetBytes(scrb_track_sig));

                HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm("MD5");
                CryptographicHash     objHash    = objAlgProv.CreateHash();
                IBuffer buffSig = CryptographicBuffer.ConvertStringToBinary(scrb_track_sig, BinaryStringEncoding.Utf8);
                objHash.Append(buffSig);
                IBuffer buffSighash = objHash.GetValueAndReset();

                scrb_track_sig = CryptographicBuffer.EncodeToHexString(buffSighash);

                HttpClient cli = new HttpClient();
                cli.DefaultRequestHeaders.ExpectContinue = false; //important
                string track_love = @"method=track.love&track=" + id3.Title + @"&artist=" + id3.Artist + @"&api_key=" + Globalv.lfm_api_key + @"&api_sig=" + scrb_track_sig + @"&sk=" + Globalv.session_key;

                cli.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                HttpContent tscr = new StringContent(track_love);

                tscr.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

                var loved_resp = await cli.PostAsync(new Uri("http://ws.audioscrobbler.com/2.0", UriKind.Absolute), tscr);

                return(await loved_resp.Content.ReadAsStringAsync());
            }
            catch (Exception) { return(null); }
        }
示例#15
0
        private void pageRoot_Loaded_1(object sender, RoutedEventArgs e)
        {
            if (MediaControl.IsPlaying)
            {
                BG1.Begin();
                id3            = Playlist.NowPlaying[0];
                SongTitle.Text = id3.Title;
                Artist.Text    = id3.Artist;
            }
            else
            {
                SongTitle.Text = "Play a song now!";
                Artist.Text    = "Swipe up from bottom for more options!";
            }

            if (Security._vault.RetrieveAll().Count != 0)
            {
                Scrobble.SetValue(AutomationProperties.NameProperty, "Last.fm Signout");
                PasswordCredential rt = Security._vault.Retrieve("Session Key", "user");
                rt.RetrievePassword();
                Globalv.session_key = rt.Password;
            }

            /*
             * if (Globalv.session_key != null)
             *  LoginBtn.Content = "Logoff";
             * else
             *  LoginBtn.Content = "Login";
             */
        }
示例#16
0
        private async System.Threading.Tasks.Task <Song> CreateSongFromFileAsync(StorageFile file)
        {
            if (file != null)
            {
                MusicProperties musicProperties = await file.Properties.GetMusicPropertiesAsync();

                BitmapImage image = await GetThumbnail(file);

                Song song = new Song
                {
                    Title      = musicProperties.Title,
                    Artist     = musicProperties.Artist,
                    Duration   = musicProperties.Duration,
                    AlbumName  = musicProperties.Album,
                    Path       = file.Path,
                    FileName   = file.Name,
                    CoverImage = image
                };
                if (string.IsNullOrEmpty(song.Title))
                {
                    song.Title = file.DisplayName;
                }
                if (string.IsNullOrEmpty(song.Artist))
                {
                    song.Artist = "Unknown Artist";
                }
                if (string.IsNullOrEmpty(song.AlbumName))
                {
                    song.AlbumName = "Unknown Album";
                }
                return(song);
            }
            return(null);
        }
示例#17
0
        public override async Task <IState <Episode, EpisodeEvent> > OnEvent(Episode owner, EpisodeEvent anEvent, IEventProcessor <Episode, EpisodeEvent> stateMachine)
        {
            switch (anEvent)
            {
            case EpisodeEvent.UpdateDownloadStatus:
            {
                try
                {
                    StorageFile file = await owner.GetStorageFile();

                    if (file == null)
                    {
                        return(GetState <EpisodeStatePendingDownload>());
                    }
                    MusicProperties musicProperties = await file.Properties.GetMusicPropertiesAsync();

                    owner.Duration = musicProperties.Duration;
                    if (owner.Title == null)
                    {
                        owner.Title = musicProperties.Title;
                    }
                    TouchedFiles.Instance.Add(file.Path);
                    TouchedFiles.Instance.Add(Path.GetDirectoryName(file.Path));
                    return(GetState <EpisodeStateDownloaded>());
                }
                catch (FileNotFoundException)
                {
                    return(GetState <EpisodeStatePendingDownload>());
                }
            }
            }
            return(null);
        }
示例#18
0
        private async void selectPlayButton_Click(object sender, RoutedEventArgs e)
        {
            if (list.SelectedItem == null)
            {
                return;
            }

            if (list.SelectedItem.Sign == 0)
            {
                Media.Source = new Uri("ms-appdata:///local/" + list.SelectedItem.Url);
                Uri         uri  = new Uri("ms-appdata:///local/" + list.SelectedItem.Url);
                StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);

                RandomAccessStreamReference imageStreamRef = RandomAccessStreamReference.CreateFromFile(file);
                MusicProperties             songProperties = await file.Properties.GetMusicPropertiesAsync();

                StorageItemThumbnail currentThumb = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 200, ThumbnailOptions.UseCurrentScale);

                var albumCover = new BitmapImage();
                albumCover.SetSource(currentThumb);
                album.ImageSource = albumCover;
            }
            else if (list.SelectedItem.Sign == 1)
            {
                Uri pathUri = new Uri(list.SelectedItem.Url);
                Media.Source      = pathUri;
                album.ImageSource = list.SelectedItem.Imag;
            }

            //album.ImageSource = list.SelectedItem.Imag;
            if (list.SelectedItem.Sign == 0)
            {
                Media.Source = new Uri("ms-appdata:///local/" + list.SelectedItem.Url);
            }
            else if (list.SelectedItem.Sign == 1)
            {
                Uri pathUri = new Uri(list.SelectedItem.Url);
                Media.Source = pathUri;
            }
            SmallStoryboard.Begin();
            BigStoryboard.Begin();
            PoleStoryboard.Begin();

            TimeLine.Maximum = Media.NaturalDuration.TimeSpan.TotalSeconds;
            //初始化喜欢的图片
            if (list.SelectedItem.Like == true)
            {
                var bitmap = new BitmapImage(new Uri("ms-appx:///Assets/like.png"));
                LikeButtonImage.Source = bitmap;
            }
            else
            {
                var bitmap = new BitmapImage(new Uri("ms-appx:///Assets/unlike.png"));
                LikeButtonImage.Source = bitmap;
            }

            PlayPauseButton.Icon  = new SymbolIcon(Symbol.Pause);
            PlayPauseButton.Label = "Pause";
            PlayPauseButtonFlag   = 1;
        }
示例#19
0
        private async Task ListView_Songs(ObservableCollection <StorageFile> files)
        {
            foreach (var song in files)
            {
                MusicProperties song_Properties = await song.Properties.GetMusicPropertiesAsync();

                StorageItemThumbnail current_Thumb = await song.GetThumbnailAsync(
                    ThumbnailMode.MusicView,
                    200,
                    ThumbnailOptions.UseCurrentScale);

                BitmapImage album_cover = new BitmapImage();
                album_cover.SetSource(current_Thumb);
                Music music = new Music();
                music.Title  = song_Properties.Title;
                music.Artist = song_Properties.Artist;
                music.Cover  = album_cover;
                localFolder  = ApplicationData.Current.LocalFolder;
                fileCopy     = await song.CopyAsync(localFolder, song.Name, NameCollisionOption.ReplaceExisting);

                music.Music_Path  = song.Name;
                music.id          = num;
                music.SongFile    = song;
                music.ForeColor   = transParent;
                music.album_title = song_Properties.Album;
                use_music.Add(music);
                num++;
            }
            allsong_count = use_music.Count;
        }
示例#20
0
 internal Song(Album album, Artist artist, Genre genre, MusicProperties musicProperties)
 {
     this.album           = album;
     this.artist          = artist;
     this.genre           = genre;
     this.musicProperties = musicProperties;
 }
        private async Task OpenMediaFile(StorageFile file)
        {
            _player.Source = MediaSource.CreateFromStorageFile(file);
            MusicProperties musicProps = await file.Properties.GetMusicPropertiesAsync();

            nowPlaying.Text = $"Now playing {musicProps.Title} by {musicProps.Artist}";
        }
示例#22
0
        private async Task <Dictionary <string, string> > GetProperties(StorageFile temporaryFile, CancellationToken cancellationToken)
        {
            StorageItemContentProperties properties = temporaryFile.Properties;
            MusicProperties musicProperties         = await properties.GetMusicPropertiesAsync();

            VideoProperties videoProperties = await properties.GetVideoPropertiesAsync();

            BasicProperties basicProperties = await temporaryFile.GetBasicPropertiesAsync();

            CancelTask(cancellationToken);

            Dictionary <string, string> tempDictionary = new Dictionary <string, string>();

            tempDictionary["Display Name"]        = temporaryFile.DisplayName;
            tempDictionary["File Type"]           = temporaryFile.FileType;
            tempDictionary["Current Folder Path"] = temporaryFile.FolderRelativeId;
            tempDictionary["Size"]           = string.Format("{0:0.00}", (Convert.ToDouble(basicProperties.Size) / 1048576d)) + " Mb";
            tempDictionary["Creation Date"]  = temporaryFile.DateCreated.ToString();
            tempDictionary["Modified Date"]  = basicProperties.DateModified.ToString();
            tempDictionary["Audio Bit Rate"] = musicProperties.Bitrate + " bps";
            tempDictionary["Length"]         = videoProperties.Duration.ToString("hh\\:mm\\:ss");
            tempDictionary["Frame Width"]    = videoProperties.Width + "";
            tempDictionary["Frame Height"]   = videoProperties.Height + "";
            tempDictionary["Orientation"]    = videoProperties.Orientation + "";
            tempDictionary["Total Bit Rate"] = videoProperties.Bitrate + " bps";

            CancelTask(cancellationToken);

            return(tempDictionary);
        }
        private async Task PopulateSongList(List <StorageFile> files)
        {
            int id = 0;

            foreach (var file in files)
            {
                MusicProperties songProperties = await file.Properties.GetMusicPropertiesAsync();

                StorageItemThumbnail currentThumb = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 200, ThumbnailOptions.UseCurrentScale);

                var albumCover = new BitmapImage();
                albumCover.SetSource(currentThumb);

                /*var song = new Song();
                 * song.Id = id;
                 * song.Title = songProperties.Title;
                 * song.Artist = songProperties.Artist;
                 * song.Album = songProperties.Album;
                 * song.AlbumCover = albumCover;
                 * song.SongFile = file;
                 * Songs.Add(song);*/

                var song = new Song()
                {
                    Id         = id,
                    Title      = songProperties.Title,
                    Artist     = songProperties.Artist,
                    Album      = songProperties.Album,
                    AlbumCover = albumCover,
                    SongFile   = file
                };
                Songs.Add(song);
                id++;
            }
        }
示例#24
0
        public LocalSong(MusicProperties musicProps)
        {
            Title       = CleanText(musicProps.Title);
            AlbumName   = CleanText(musicProps.Album);
            AlbumArtist = CleanText(musicProps.AlbumArtist);
            ArtistName  = CleanText(musicProps.Artist);

            BitRate     = (int)musicProps.Bitrate;
            Duration    = musicProps.Duration;
            Genre       = musicProps.Genre.FirstOrDefault();
            TrackNumber = (int)musicProps.TrackNumber;

            if (!string.IsNullOrEmpty(ArtistName) || !string.IsNullOrEmpty(AlbumArtist))
            {
                ArtistId = Convert.ToBase64String(Encoding.UTF8.GetBytes((AlbumArtist ?? ArtistName).ToLower()));
            }
            if (!string.IsNullOrEmpty(AlbumName))
            {
                AlbumId = Convert.ToBase64String(Encoding.UTF8.GetBytes(AlbumName.ToLower()));
            }
            if (!string.IsNullOrEmpty(Title))
            {
                Id = Convert.ToBase64String(Encoding.UTF8.GetBytes(Title.ToLower())) + ArtistId + AlbumId;
            }

            if (musicProps.Rating > 1)
            {
                HeartState = HeartState.Like;
            }
        }
示例#25
0
 public Song(StorageFile musicFile, MusicProperties properties)
 {
     MusicFile = musicFile;
     Artist    = properties.Artist;
     Title     = properties.Title;
     Album     = properties.Album;
 }
        public async Task <MusicMetadata> CreateMusicMetadata(MusicProperties properties, CancellationToken cancellationToken)
        {
            var propertiesToRetrieve = new List <string>();

            AddPropertiesToRetrieve(propertiesToRetrieve);
            var customProperties = await properties.RetrievePropertiesAsync(propertiesToRetrieve).AsTask(cancellationToken).ConfigureAwait(false);

            TimeSpan duration = ReadDuration(properties, customProperties);
            uint     bitrate  = ReadBitrate(properties, customProperties);

            if (!IsSupported || (duration == TimeSpan.Zero && bitrate == 0))
            {
                return(MusicMetadata.CreateUnsupported(duration, bitrate));
            }

            return(new MusicMetadata(duration, bitrate)
            {
                Title = ReadTitle(properties, customProperties),
                Artists = ToSaveArray(ReadArtists(properties, customProperties)),
                Rating = ReadRating(properties, customProperties),
                Album = ReadAlbum(properties, customProperties),
                TrackNumber = ReadTrackNumber(properties, customProperties),
                Year = ReadYear(properties, customProperties),
                Genre = ToSaveArray(ReadGenre(properties, customProperties)),
                AlbumArtist = ReadAlbumArtist(properties, customProperties),
                Publisher = ReadPublisher(properties, customProperties),
                Subtitle = ReadSubtitle(properties, customProperties),
                Composers = ToSaveArray(ReadComposers(properties, customProperties)),
                Conductors = ToSaveArray(ReadConductors(properties, customProperties))
            });
        }
        private async Task LoadFile(StorageFile file)
        {
            if (isCanceled)
            {
                return;
            }

            if (Utilities.IsSupportedFileType(file.FileType))
            {
                StorageItemContentProperties fileProperties = file.Properties;

                MusicProperties musicProperties = await fileProperties.GetMusicPropertiesAsync();

                IDictionary <string, object> artistProperties = await fileProperties.RetrievePropertiesAsync(RealMusicProperties);

                object artists = null;
                artistProperties.TryGetValue("System.Music.Artist", out artists);

                string[] artistsAsArray = DebugHelper.CastAndAssert <string[]>(artists);

                string artistName = string.Empty;

                if (artistsAsArray != null && artistsAsArray.Length > 0)
                {
                    artistName = artistsAsArray[0];
                }

                if (this.TrackScanned != null)
                {
                    this.TrackScanned(this, new TrackScannedEventArgs(new StorageProviderSong(file.Path, musicProperties, artistName)));
                }
            }
        }
示例#28
0
        private async void show_Click(object sender, RoutedEventArgs e)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                MyMedia.MediaPlayer.MediaEnded  += MediaPlayer_MediaEnded;
                MyMedia.MediaPlayer.MediaOpened += MediaPlayer_MediaOpened;
            });

            playlist = await PickPlayListAsync();

            if (playlist != null)
            {
                list_result.Items.Clear();
                result = "播放列表中的歌曲:" + playlist.Files.Count.ToString() + "\n";
                a.Text = result;
                foreach (var file in playlist.Files)
                {
                    result = "";
                    MusicProperties pros = await file.Properties.GetMusicPropertiesAsync();

                    result += pros.Title + "\n";
                    result += "专辑: " + pros.Album + "\n";
                    result += "艺术家: " + pros.Artist + "\n";
                    result += "时长: " + pros.Duration.ToString().Split('.')[0];
                    list_result.Items.Add(result);
                }
            }
        }
示例#29
0
        // 3.Pluck off meta data from selected songs HELPER method
        private async Task PopulateSongList(List <StorageFile> files)
        {
            int id = 0;

            foreach (var file in files)
            {
                MusicProperties songProperties = await file.Properties.GetMusicPropertiesAsync();

                StorageItemThumbnail currentThumb = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 200, ThumbnailOptions.UseCurrentScale);

                var albumCover = new BitmapImage();
                albumCover.SetSource(currentThumb);

                var song = new Song(); // Create a new Song Object from the Class Song.
                song.Id         = id;
                song.Title      = songProperties.Title;
                song.Artist     = songProperties.Artist;
                song.Album      = songProperties.Album;
                song.AlbumCover = albumCover;
                song.SongFile   = file;

                Songs.Add(song); // Then add the song to the instance of our observableCollection of Song Class
                id++;
            }
        }
示例#30
0
        private async Task PopulateSongList(List <StorageFile> files)
        {
            int id = 0;

            foreach (var file in files)
            {
                MusicProperties songProperties = await file.Properties.GetMusicPropertiesAsync();

                StorageItemThumbnail currentThumb = await file.GetThumbnailAsync(
                    ThumbnailMode.MusicView,
                    200,
                    ThumbnailOptions.UseCurrentScale);

                var albumCover = new BitmapImage();
                albumCover.SetSource(currentThumb);
                //Getting Songs and their data .. Xaml Get and Set
                var song = new Song();
                song.Id         = id;
                song.Title      = songProperties.Title;
                song.Artist     = songProperties.Artist;
                song.Album      = songProperties.Album;
                song.AlbumCover = albumCover;
                song.SongFile   = file;

                Songs.Add(song);
                id++;
            }
        }
示例#31
0
        private void PlatformLoad(Action<int> progressCallback)
        {
#if !WINDOWS_UAP
            Task.Run(async () =>
            {
                if (musicFolder == null)
                {
                    try
                    {
                        musicFolder = KnownFolders.MusicLibrary;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("Failed to access Music Library: " + e.Message);
                        albumCollection = new AlbumCollection(new List<Album>());
                        songCollection = new SongCollection(new List<Song>());
                        return;
                    }
                }
                    
            
                var files = new List<StorageFile>();
                await this.GetAllFiles(musicFolder, files);

                var songList = new List<Song>();
                var albumList = new List<Album>();

                var artists = new Dictionary<string, Artist>();
                var albums = new Dictionary<string, Album>();
                var genres = new Dictionary<string, Genre>();

                var cache = new Dictionary<string, MusicProperties>();

                // Read cache
                var cacheFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(CacheFile, CreationCollisionOption.OpenIfExists);
                using (var stream = new BinaryReader(await cacheFile.OpenStreamForReadAsync()))
                    try
                    {
                        for (; stream.BaseStream.Position < stream.BaseStream.Length; )
                        {
                            var entry = MusicProperties.Deserialize(stream);
                            cache.Add(entry.Path, entry);
                        }
                    }
                    catch { }

                // Write cache
                cacheFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(CacheFile, CreationCollisionOption.ReplaceExisting);
                using (var stream = new BinaryWriter(await cacheFile.OpenStreamForWriteAsync()))
                {
                    int prevProgress = 0;

                    for (int i = 0; i < files.Count; i++)
                    {
                        var file = files[i];
                        try
                        {
                            MusicProperties properties;
                            if (!(cache.TryGetValue(file.Path, out properties) && properties.TryMatch(file)))
                                properties = new MusicProperties(file);
                            properties.Serialize(stream);

                            if (string.IsNullOrWhiteSpace(properties.Title))
                                continue;

                            Artist artist;
                            if (!artists.TryGetValue(properties.Artist, out artist))
                            {
                                artist = new Artist(properties.Artist);
                                artists.Add(artist.Name, artist);
                            }

                            Artist albumArtist;
                            if (!artists.TryGetValue(properties.AlbumArtist, out albumArtist))
                            {
                                albumArtist = new Artist(properties.AlbumArtist);
                                artists.Add(albumArtist.Name, albumArtist);
                            }

                            Genre genre;
                            if (!genres.TryGetValue(properties.Genre, out genre))
                            {
                                genre = new Genre(properties.Genre);
                                genres.Add(genre.Name, genre);
                            }

                            Album album;
                            if (!albums.TryGetValue(properties.Album, out album))
                            {
                                var thumbnail = Task.Run(async () => await properties.File.GetThumbnailAsync(ThumbnailMode.MusicView, 300, ThumbnailOptions.ResizeThumbnail)).Result;
                                album = new Album(new SongCollection(), properties.Album, albumArtist, genre, thumbnail.Type == ThumbnailType.Image ? thumbnail : null);
                                albums.Add(album.Name, album);
                                albumList.Add(album);
                            }

                            var song = new Song(album, artist, genre, properties);
                            song.Album.Songs.Add(song);
                            songList.Add(song);
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine("MediaLibrary exception: " + e.Message);
                        }

                        int progress = 100 * i / files.Count;
                        if (progress > prevProgress)
                        {
                            prevProgress = progress;
                            if (progressCallback != null)
                                progressCallback.Invoke(progress);
                        }
                    }
                }

                if (progressCallback != null)
                    progressCallback.Invoke(100);

                albumCollection = new AlbumCollection(albumList);
                songCollection = new SongCollection(songList);
            }).Wait();
#endif
        }