Ejemplo n.º 1
0
        private async Task Initialize()
        {
            using (IRandomAccessStream Stream = await MediaFile.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read).ConfigureAwait(true))
            {
                Source = MediaSource.CreateFromStream(Stream, MIMEDictionary[MediaFile.Type.ToLower()]);
                MediaPlaybackItem Item = new MediaPlaybackItem(Source);

                switch (MediaFile.Type.ToLower())
                {
                case ".mp3":
                case ".flac":
                case ".wma":
                case ".m4a":
                {
                    MusicCover.Visibility = Visibility.Visible;

                    MediaItemDisplayProperties Props = Item.GetDisplayProperties();
                    Props.Type = Windows.Media.MediaPlaybackType.Music;
                    Props.MusicProperties.Title       = MediaFile.DisplayName;
                    Props.MusicProperties.AlbumArtist = GetArtist();

                    Item.ApplyDisplayProperties(Props);

                    if (await GetMusicCoverAsync().ConfigureAwait(true) is BitmapImage Thumbnail)
                    {
                        Cover.Source     = Thumbnail;
                        Cover.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        Cover.Visibility = Visibility.Collapsed;
                    }

                    Display.Text     = $"{Globalization.GetString("Media_Tip_Text")} {MediaFile.DisplayName}";
                    MVControl.Source = Item;
                    break;
                }

                default:
                {
                    MusicCover.Visibility = Visibility.Collapsed;

                    MediaItemDisplayProperties Props = Item.GetDisplayProperties();
                    Props.Type = Windows.Media.MediaPlaybackType.Video;
                    Props.VideoProperties.Title = MediaFile.DisplayName;
                    Item.ApplyDisplayProperties(Props);

                    MVControl.Source = Item;
                    break;
                }
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Build a media item and add it to the list
        /// </summary>
        /// <param name="track">Track to build into a media item</param>
        private void BuildMediaItem(BaseTrack track)
        {
            // Create a media binding for later (this is used to
            // load the track streams as we need them).
            var binder = new MediaBinder
            {
                Token = JsonConvert.SerializeObject(track)
            };

            binder.Binding += BindMediaSource;

            // Create the source, bind track metadata and use it to
            // create a playback item
            var source            = MediaSource.CreateFromMediaBinder(binder);
            var mediaPlaybackItem = new MediaPlaybackItem(track.AsMediaSource(source));

            // Apply display properties to this item
            var displayProperties = mediaPlaybackItem.GetDisplayProperties();

            displayProperties.Type = MediaPlaybackType.Music;
            displayProperties.MusicProperties.Title  = track.Title;
            displayProperties.MusicProperties.Artist = track.User.Username;
            displayProperties.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri(track.ThumbnailUrl));

            // Apply the properties
            mediaPlaybackItem.ApplyDisplayProperties(displayProperties);

            // Add this item to the list
            _mediaPlaybackList.Items.Add(mediaPlaybackItem);
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            TrackObject o = (TrackObject)e.Parameter;

            if (o == null)
            {
                o = MainPage.currentSong;
                this.songArtist.Text          = o.trackArtistName;
                this.songTitle.Text           = o.trackTitle;
                this.songArtwork.Source       = o.albumCoverImage;
                this.songAlbumArtistName.Text = o.album.artist.name;
                this.songAlbumName.Text       = o.album.name;

                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    Uri webLink                      = new Uri(o.trackStreamURL);
                    MediaPlaybackItem song           = new MediaPlaybackItem(MediaSource.CreateFromUri(webLink));
                    MediaItemDisplayProperties props = song.GetDisplayProperties();
                    props.Type = MediaPlaybackType.Music;
                    props.MusicProperties.Title  = o.trackTitle;
                    props.MusicProperties.Artist = o.trackArtistName;
                    props.MusicProperties.Genres.Add(o.track.genreprimary);
                    props.MusicProperties.Genres.Add(o.track.genresecondary);
                    props.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri(o.albumCoverURL));
                    song.ApplyDisplayProperties(props);
                    mediaPlayer.Source       = song;
                    MainPage.nowPlaying.Text = "Now Playing: \"" + o.trackArtistName + " ~ " + o.trackTitle + "\"";
                });
            }
            else
            {
                this.songArtist.Text          = o.trackArtistName;
                this.songTitle.Text           = o.trackTitle;
                this.songArtwork.Source       = o.albumCoverImage;
                this.songAlbumArtistName.Text = o.album.artist.name;
                this.songAlbumName.Text       = o.album.name;

                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    if (MainPage.currentSong != o)
                    {
                        MainPage.currentSong             = o;
                        Uri webLink                      = new Uri(o.trackStreamURL);
                        MediaPlaybackItem song           = new MediaPlaybackItem(MediaSource.CreateFromUri(webLink));
                        MediaItemDisplayProperties props = song.GetDisplayProperties();
                        props.Type = MediaPlaybackType.Music;
                        props.MusicProperties.Title  = o.trackTitle;
                        props.MusicProperties.Artist = o.trackArtistName;
                        props.MusicProperties.Genres.Add(o.track.genreprimary);
                        props.MusicProperties.Genres.Add(o.track.genresecondary);
                        props.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri(o.albumCoverURL));
                        song.ApplyDisplayProperties(props);
                        mediaPlayer.Source       = song;
                        MainPage.nowPlaying.Text = "Now Playing: \"" + o.trackArtistName + " ~ " + o.trackTitle + "\"";
                    }
                });
            }
        }
Ejemplo n.º 4
0
        private async void loadProperties(MediaPlaybackItem cur)
        {
            var mediaItem = cur.Source;
            var file      = mediaItem.CustomProperties["FILE"] as StorageFile;

            if (file != null)
            {
                var extraProperties = await file.Properties.GetMusicPropertiesAsync();

                var props = cur.GetDisplayProperties();
                props.MusicProperties.AlbumArtist = extraProperties.AlbumArtist;
                props.MusicProperties.AlbumTitle  = extraProperties.Album;
                //props.MusicProperties.AlbumTrackCount = extraProperties.;
                props.MusicProperties.Artist = extraProperties.Artist;
                foreach (var t in extraProperties.Genre)
                {
                    props.MusicProperties.Genres.Add(t);
                }
                props.MusicProperties.Title       = extraProperties.Title;
                props.MusicProperties.TrackNumber = extraProperties.TrackNumber;

                cur.ApplyDisplayProperties(props);
                // TODO keep??
                mediaItem.CustomProperties["FILE"] = null;
            }
        }
Ejemplo n.º 5
0
        private async Task UpdateSystemMediaTransportControlsAndThumbnail(LibraryItem libraryItemToPlay, MediaPlaybackItem mediaPlaybackItem,
                                                                          StorageFile fileWithThumbnail = null)
        {
            MediaItemDisplayProperties props = mediaPlaybackItem.GetDisplayProperties();

            props.Type = Windows.Media.MediaPlaybackType.Music;
            props.MusicProperties.Title = libraryItemToPlay.Name;

            if (libraryItemToPlay.Artist != null)
            {
                props.MusicProperties.Artist = libraryItemToPlay.Artist;
            }

            if (libraryItemToPlay.Album != null)
            {
                props.MusicProperties.AlbumTitle = libraryItemToPlay.Album;
            }

            if (fileWithThumbnail != null)
            {
                StorageItemThumbnail thumbnail = await GetAndSetThumbnail(fileWithThumbnail);

                if (thumbnail != null)
                {
                    props.Thumbnail = RandomAccessStreamReference.CreateFromStream(thumbnail);
                }
            }

            mediaPlaybackItem.ApplyDisplayProperties(props);
        }
Ejemplo n.º 6
0
        public static async Task <MediaPlaybackItem> ToMediaItem(MusicItem m)
        {
            var file = await StorageFile.GetFileFromPathAsync(m.FilePath);

            var stream = await file.OpenAsync(FileAccessMode.Read);

            var source = MediaSource.CreateFromStream(stream, file.ContentType);

            source.CustomProperties["FilePath"]       = m.FilePath;
            source.CustomProperties["CoverImagePath"] = m.CoveImagePath;
            source.CustomProperties["Title"]          = m.Title;
            source.CustomProperties["Artist"]         = m.Artist;
            source.CustomProperties["Album"]          = m.Album;
            var item = new MediaPlaybackItem(source);

            var displayproperties = item.GetDisplayProperties();

            displayproperties.Type = MediaPlaybackType.Music;
            displayproperties.MusicProperties.Title      = m.Title;
            displayproperties.MusicProperties.Artist     = m.Artist;
            displayproperties.MusicProperties.AlbumTitle = m.Album;
            if (m.CoveImagePath != null)
            {
                displayproperties.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri(m.CoveImagePath));
            }
            item.ApplyDisplayProperties(displayproperties);

            return(item);
        }
        public virtual MediaPlaybackItem ToPlaybackItem()
        {
            // Create the media source from the Uri
            var source = MediaSource.CreateFromUri(MediaUri);

            // Create a configurable playback item backed by the media source
            var playbackItem = new MediaPlaybackItem(source);

            // Populate display properties for the item that will be used
            // to automatically update SystemMediaTransportControls when
            // the item is playing.
            var displayProperties = playbackItem.GetDisplayProperties();

            // Populate thumbnail
            if (PreviewImageUri != null)
            {
                displayProperties.Thumbnail = RandomAccessStreamReference.CreateFromUri(PreviewImageUri);
            }

            // Apply properties to the playback item
            playbackItem.ApplyDisplayProperties(displayProperties);

            // It's often useful to save a reference or ID to correlate
            // a particular MediaPlaybackItem with the item from the
            // backing data model. CustomProperties stores serializable
            // types, so here we use the media item's URI as the
            // playback item's unique ID. You are also free to use your own
            // external dictionary if you want to reference non-serializable
            // types.
            source.CustomProperties[MediaItem.MediaItemIdKey] = ItemId;

            return(playbackItem);
        }
Ejemplo n.º 8
0
        private void PlayByURL(Uri mediaURL, string title, bool audio)
        {
            if (Player.PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
            {
                Player.Pause();
            }

            try
            {
                _mediaSource       = MediaSource.CreateFromUri(mediaURL);
                _mediaPlaybackItem = new MediaPlaybackItem(_mediaSource);
                _mediaPlaybackItem.AutoLoadedDisplayProperties = AutoLoadedDisplayPropertyKind.MusicOrVideo;
                var props = _mediaPlaybackItem.GetDisplayProperties();
                if (audio)
                {
                    props.Thumbnail             = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/image_sound_wave.png"));
                    props.Type                  = Windows.Media.MediaPlaybackType.Music;
                    props.MusicProperties.Title = title;
                }
                else
                {
                    props.Type = Windows.Media.MediaPlaybackType.Video;
                    props.VideoProperties.Title = title;
                }
                _mediaPlaybackItem.ApplyDisplayProperties(props);
                Player.Source = _mediaPlaybackItem;
                Player.Play();
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 9
0
        private MediaPlaybackItem GetPlaybackItem(Message message)
        {
            var token = message.Id.ToString();
            var file  = GetFile(message);

            var binder = new MediaBinder();

            binder.Token    = token;
            binder.Binding += Binder_Binding;

            var source = MediaSource.CreateFromMediaBinder(binder);
            var item   = new MediaPlaybackItem(source);

            source.CustomProperties["file"]    = file.Id;
            source.CustomProperties["message"] = message.Id;
            source.CustomProperties["chat"]    = message.ChatId;
            source.CustomProperties["token"]   = token;

            if (message.Content is MessageAudio audio)
            {
                var props = item.GetDisplayProperties();
                props.Type = MediaPlaybackType.Music;
                props.MusicProperties.Title  = string.IsNullOrEmpty(audio.Audio.Title) ? Strings.Resources.AudioUnknownTitle : audio.Audio.Title;
                props.MusicProperties.Artist = string.IsNullOrEmpty(audio.Audio.Performer) ? Strings.Resources.AudioUnknownArtist : audio.Audio.Performer;

                item.ApplyDisplayProperties(props);
            }

            _mapping[token] = message;

            return(item);
        }
        public virtual MediaPlaybackItem ToPlaybackItem()
        {
            // Create the media source from the Uri
            var source = MediaSource.CreateFromUri(MediaUri);

            // Create a configurable playback item backed by the media source
            var playbackItem = new MediaPlaybackItem(source);

            // Populate display properties for the item that will be used
            // to automatically update SystemMediaTransportControls when
            // the item is playing.
            var displayProperties = playbackItem.GetDisplayProperties();

            // Populate thumbnail
            if (PreviewImageUri != null)
                displayProperties.Thumbnail = RandomAccessStreamReference.CreateFromUri(PreviewImageUri);

            // Apply properties to the playback item
            playbackItem.ApplyDisplayProperties(displayProperties);

            // It's often useful to save a reference or ID to correlate
            // a particular MediaPlaybackItem with the item from the
            // backing data model. CustomProperties stores serializable
            // types, so here we use the media item's URI as the
            // playback item's unique ID. You are also free to use your own
            // external dictionary if you want to reference non-serializable
            // types.
            source.CustomProperties[MediaItem.MediaItemIdKey] = ItemId;

            return playbackItem;
        }
Ejemplo n.º 11
0
        private async Task <bool> PreparePlayback(string text, bool easter)
        {
            bool done = false;

            SpeechSynthesisStream synthStream = await synth.SynthesizeTextToStreamAsync(text);

            MediaSource       mediaSource  = MediaSource.CreateFromStream(synthStream, "audio");
            MediaPlaybackItem playbackItem = new MediaPlaybackItem(mediaSource);

            MediaItemDisplayProperties mediaProps = playbackItem.GetDisplayProperties();

            mediaProps.Type = MediaPlaybackType.Music;
            mediaProps.MusicProperties.Artist = "Talkinator"; // TODO Get name of selected Voice and paste it as Talkinator 'Bob'
            mediaProps.MusicProperties.Title  = "Spoken text";
            //mediaProps.MusicProperties.Genres.Add("Speech");
            playbackItem.ApplyDisplayProperties(mediaProps);

            _player.SystemMediaTransportControls.IsEnabled = true;

            _player.Source = playbackItem;

            if (easter == false)
            {
                if (_loopEnabled == true)
                {
                    _player.IsLoopingEnabled = true;
                }
            }

            _player.AutoPlay    = true;
            _player.MediaEnded += _player_MediaEnded;

            done = true;
            return(done);
        }
Ejemplo n.º 12
0
        private async void FontIcon_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            FontIcon FI = sender as FontIcon;

            SingleMusicControl.SelectedItem = ((FontIcon)sender).DataContext;
            SearchSingleMusic SSM = SingleMusicList[SingleMusicControl.SelectedIndex];

            if (((SolidColorBrush)FI.Foreground).Color == Colors.White)
            {
                string MusicURL = (await NetEaseMusic.GetSongsUrlAsync(SingleMusicList[SingleMusicControl.SelectedIndex].SongID)).Data[0].Url;
                if (MusicURL == null)
                {
                    ContentDialog dialog = new ContentDialog
                    {
                        Title           = "抱歉",
                        Content         = "当前歌曲暂时无法播放",
                        CloseButtonText = "确定",
                        Background      = Application.Current.Resources["DialogAcrylicBrush"] as Brush
                    };
                    await dialog.ShowAsync();

                    return;
                }
                FI.Glyph      = "\uEB52";
                FI.Foreground = new SolidColorBrush(Colors.Red);
                MusicList.ThisPage.FavouriteMusicCollection.Add(new PlayList(SSM.MusicName, SSM.Artist, SSM.Album, SSM.Duration, SSM.ImageUrl, SSM.SongID[0], SSM.MVid));
                MediaPlaybackItem Item = new MediaPlaybackItem(MediaSource.CreateFromUri(new Uri(MusicURL)));

                MediaItemDisplayProperties Props = Item.GetDisplayProperties();
                Props.Type = Windows.Media.MediaPlaybackType.Music;
                Props.MusicProperties.Title  = SSM.MusicName;
                Props.MusicProperties.Artist = SSM.Artist;
                Item.ApplyDisplayProperties(Props);
                MediaPlayList.FavouriteSongList.Items.Add(Item);

                await SQLite.GetInstance().SetMusicDataAsync(SSM.MusicName, SSM.Artist, SSM.Album, SSM.Duration, SSM.ImageUrl, SSM.SongID[0], SSM.MVid);
            }
            else
            {
                FI.Glyph      = "\uEB51";
                FI.Foreground = new SolidColorBrush(Colors.White);
                for (int i = 0; i < MusicList.ThisPage.FavouriteMusicCollection.Count; i++)
                {
                    if (MusicList.ThisPage.FavouriteMusicCollection[i].SongID == SSM.SongID[0])
                    {
                        await SQLite.GetInstance().DeleteMusicAsync(MusicList.ThisPage.FavouriteMusicCollection[i]);

                        MusicList.ThisPage.FavouriteMusicCollection.RemoveAt(i);
                        MediaPlayList.FavouriteSongList.Items.RemoveAt(i);
                        break;
                    }
                }
            }
        }
Ejemplo n.º 13
0
        private async void PlayAll_Click(object sender, RoutedEventArgs e)
        {
            bool ExistCannotPlay = false;

            if (MediaPlayList.AlbumSongList.Items.Count != 0)
            {
                MediaPlayList.AlbumSongBackup.Clear();
                MediaPlayList.AlbumSongList.Items.Clear();
            }

            MusicPage.ThisPage.MediaControl.AutoPlay           = true;
            MusicPage.ThisPage.MediaControl.MediaPlayer.Source = MediaPlayList.AlbumSongList;

            foreach (SearchSingleMusic item in AlbumCollection)
            {
                MediaPlayList.AlbumSongBackup.Add(new SearchSingleMusic(item.MusicName, item.Artist, item.Album, item.Duration, item.SongID[0], item.ImageUrl, item.MVid));

                string uri = (await NeteaseMusicAPI.GetInstance().GetSongsUrlAsync(item.SongID)).Data[0].Url;
                if (uri == null)
                {
                    ExistCannotPlay = true;
                    continue;
                }

                //采用延迟加载技术,仅当该歌曲处于即将播放状态时才调用Binder_Binding加载资源
                MediaBinder binder = new MediaBinder
                {
                    Token = uri
                };
                binder.Binding += Binder_Binding;
                MediaPlaybackItem Item = new MediaPlaybackItem(MediaSource.CreateFromMediaBinder(binder));

                //与系统的SMTC集成
                MediaItemDisplayProperties Props = Item.GetDisplayProperties();
                Props.Type = Windows.Media.MediaPlaybackType.Music;
                Props.MusicProperties.Title  = item.MusicName;
                Props.MusicProperties.Artist = item.Album;
                Item.ApplyDisplayProperties(Props);

                MediaPlayList.AlbumSongList.Items.Add(Item);
            }
            if (ExistCannotPlay)
            {
                ExistCannotPlay = false;
                ContentDialog dialog = new ContentDialog
                {
                    Title           = "抱歉",
                    Content         = "部分歌曲暂时无法播放,已自动忽略",
                    CloseButtonText = "确定",
                    Background      = Application.Current.Resources["DialogAcrylicBrush"] as Brush
                };
                await dialog.ShowAsync();
            }
        }
Ejemplo n.º 14
0
        private MediaPlaybackItem _createMediaPlaybackItem(MediaSource source, MusicModel model)
        {
            source.CustomProperties["model"] = JsonSerializer.Serialize(model);
            var item = new MediaPlaybackItem(source);
            //Set STMC
            var props = item.GetDisplayProperties();

            props.Type = MediaPlaybackType.Music;
            props.MusicProperties.Title = model.Title;
            item.ApplyDisplayProperties(props);
            return(item);
        }
Ejemplo n.º 15
0
        public static async Task <MediaPlaybackItem> CreateMediaPlaybackItemAsync(StorageFile song)
        {
            MediaPlaybackItem item = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(song));

            MediaItemDisplayProperties properties      = item.GetDisplayProperties();
            MusicProperties            musicProperties = await song.Properties.GetMusicPropertiesAsync();

            properties.Type = Windows.Media.MediaPlaybackType.Music;
            properties.MusicProperties.Artist = musicProperties.Artist;
            properties.MusicProperties.Title  = musicProperties.Title;

            item.ApplyDisplayProperties(properties);
            return(item);
        }
Ejemplo n.º 16
0
        private async void BtnPlay_ClickAsync(object sender, RoutedEventArgs e)
        {
            if (!User.IsLogIn())
            {
                await new ContentDialog
                {
                    Title             = "Информация",
                    Content           = "Авторизуйтесь в системе для получения возможности прослушивания песен",
                    PrimaryButtonText = "ОК"
                }.ShowAsync();
                return;
            }
            _mediaElement.MediaPlayer.Pause();
            IRandomAccessStream src = null;
            await Task.Run(() =>
            {
                App app = Application.Current as App;
                try
                {
                    using (SqlConnection connection = new SqlConnection(app.GetConnectionString()))
                    {
                        connection.Open();
                        SqlCommand cmd  = connection.CreateCommand();
                        cmd.CommandText = string.Format(DBQueryCollection.QUERY_FOR_MUSIC_SRC, _track.SrcId.ToString());
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            reader.Read();
                            src = WindowsRuntimeStreamExtensions.AsRandomAccessStream(reader.GetStream(0));
                        }
                    }
                }
                catch (Exception)
                {
                    ShowErrorDialog();
                    return;
                }
            });

            MediaSource                mediaSource       = MediaSource.CreateFromStream(src, "MPEG");
            MediaPlaybackItem          mediaPlaybackItem = new MediaPlaybackItem(mediaSource);
            MediaItemDisplayProperties props             = mediaPlaybackItem.GetDisplayProperties();

            props.Type = Windows.Media.MediaPlaybackType.Music;
            props.MusicProperties.Artist     = _track.Artist.Name;
            props.MusicProperties.AlbumTitle = _track.Album.Name;
            props.MusicProperties.Title      = _track.Name;
            mediaPlaybackItem.ApplyDisplayProperties(props);
            _mediaElement.MediaPlayer.Source = mediaPlaybackItem;
            _mediaElement.MediaPlayer.Play();
        }
Ejemplo n.º 17
0
        public MediaPlaybackItem ToPlaybackItem()
        {
            var source = MediaSource.CreateFromStorageFile(Music.File);

            var playbackItem = new MediaPlaybackItem(source);

            var displayProperties = playbackItem.GetDisplayProperties();

            playbackItem.ApplyDisplayProperties(displayProperties);

            source.CustomProperties[GetMediaItemIdKey] = Music.Id;

            return(playbackItem);
        }
Ejemplo n.º 18
0
        public async Task <MediaPlaybackItem> ToPlaybackItem()
        {
            // Create the media source from the Uri
            var source = MediaSource.CreateFromUri(MediaUri);

            // Create a configurable playback item backed by the media source
            var playbackItem = new MediaPlaybackItem(source);

            MediaItemDisplayProperties displayProperties = playbackItem.GetDisplayProperties();

            displayProperties.Type = MediaPlaybackType.Music;
            displayProperties.MusicProperties.Title = this.Title;
            playbackItem.ApplyDisplayProperties(displayProperties);

            return(playbackItem);
        }
Ejemplo n.º 19
0
        public virtual MediaPlaybackItem ToPlaybackItem()
        {
            var source            = MediaSource.CreateFromUri(MediaUri);
            var playbackItem      = new MediaPlaybackItem(source);
            var displayProperties = playbackItem.GetDisplayProperties();

            if (PreviewImageUri != null)
            {
                displayProperties.Thumbnail = RandomAccessStreamReference.CreateFromUri(PreviewImageUri);
            }

            playbackItem.ApplyDisplayProperties(displayProperties);
            source.CustomProperties[MediaItem.MediaItemIdKey] = ItemId;

            return(playbackItem);
        }
Ejemplo n.º 20
0
        private void BuildMediaPlaybackList()
        {
            // 建立 MediaPlaybackList,並設定 MusicProperties,讓 SMTC 更新 UI
            for (int i = 1; i < 5; i++)
            {
                MediaSource                source          = MediaSource.CreateFromUri(new Uri($"{Package.Current.InstalledLocation.Path}/WPFAndUWPSample/Assets/mp3/0{i}.mp3", UriKind.RelativeOrAbsolute));
                MediaPlaybackItem          item            = new MediaPlaybackItem(source);
                MediaItemDisplayProperties displayProperty = item.GetDisplayProperties();
                displayProperty.Type = MediaPlaybackType.Music;
                displayProperty.MusicProperties.Title       = $"0{i}.mp3";
                displayProperty.MusicProperties.AlbumArtist = "JJ";
                displayProperty.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri($"{Package.Current.InstalledLocation.Path}/WPFAndUWPSample/Assets/mp3/0{i}.jpg"));;
                item.ApplyDisplayProperties(displayProperty);

                MediaPlaybackList.Items.Add(item);
            }
        }
Ejemplo n.º 21
0
        static async Task AddSourceToPlaylistAsync(PlaylistEntry entry, int?index = null)
        {
            var source = await entry.GetSourceAsync();

            if (source == null)
            {
                return;
            }

            source.CustomProperties["entry"] = JsonConvert.SerializeObject(entry);

            var item        = new MediaPlaybackItem(source);
            var displayInfo = item.GetDisplayProperties();

            displayInfo.MusicProperties.Artist      = entry.Episode.Author;
            displayInfo.MusicProperties.AlbumArtist = entry.Episode.Author;
            displayInfo.MusicProperties.Title       = entry.Episode.Title;
            displayInfo.MusicProperties.AlbumTitle  = entry.PodcastTitle ?? "";
            displayInfo.Type = MediaPlaybackType.Music;
            try
            {
                var albumArtUri = new Uri(entry.Episode.PictureUrl);
                displayInfo.Thumbnail = RandomAccessStreamReference.CreateFromUri(albumArtUri);
            }
            catch
            {
                // Ignore error. Uri could be malformed or weird.
            }

            item.ApplyDisplayProperties(displayInfo);

            lock (Player)
            {
                if (index.HasValue && playbackList.Items.Count > index.Value)
                {
                    playbackList.Items.Insert(index.Value, item);
                }
                else
                {
                    playbackList.Items.Add(item);
                }
            }

            entry.AssociatedPlaybackItem = item;
        }
Ejemplo n.º 22
0
        private async Task <bool> PreparePlayback()
        {
            IsPreparing = true;

            // Create an audio stream of the text
            SpeechSynthesisStream synthStream;

            // Check if any text has been entered, otherwise play a secret message
            if (Text == "")
            {
                // Randomize Text
                SetSecretText();
                synthStream = await _speechSynthesizer.SynthesizeTextToStreamAsync(SecretText);
            }
            else
            {
                synthStream = await _speechSynthesizer.SynthesizeTextToStreamAsync(Text);
            }
            MediaSource mediaSource = MediaSource.CreateFromStream(synthStream, "audio");
            // Now make a PlaybackItem from this stream
            MediaPlaybackItem playbackItem = new MediaPlaybackItem(mediaSource);

            // Now set the properties of this PlaybackItem
            MediaItemDisplayProperties mediaProperties = playbackItem.GetDisplayProperties();

            mediaProperties.Type = MediaPlaybackType.Music;
            mediaProperties.MusicProperties.Artist = ("Talkinator " + ResourceExtensions.GetLocalized("VoicedBy") + " " + SelectedVoice.VoiceName);
            mediaProperties.MusicProperties.Title  = ResourceExtensions.GetLocalized("SpokenText");

            playbackItem.ApplyDisplayProperties(mediaProperties);

            // Set this to enabled to make sure the info entered above will be shown in the System UI
            _mediaPlayer.SystemMediaTransportControls.IsEnabled = true;

            // Set the created item as a Source into the MediaPlayer
            _mediaPlayer.Source = playbackItem;

            // #TODO: Implement AutoPlay as well? Need to test their importance first
            _mediaPlayer.MediaEnded += _mediaPlayer_MediaEnded;

            // #TODO: Reimplement easter eggs
            IsPreparing = false;
            return(true);
        }
        private void BuildMediaPlaybackList()
        {
            for (int i = 1; i < 5; i++)
            {
                string file = $"ms-appx:///Assets/mp3/0{i}.mp3";

                MediaSource source = MediaSource.CreateFromUri(new Uri(file, UriKind.RelativeOrAbsolute));
                MediaPlaybackItem item = new MediaPlaybackItem(source);
                MediaItemDisplayProperties displayProperty = item.GetDisplayProperties();
                displayProperty.Type = MediaPlaybackType.Music;
                displayProperty.MusicProperties.Title = $"0{i}.mp3";
                displayProperty.MusicProperties.AlbumArtist = "JJ";
                displayProperty.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri($"ms-appx:///Assets/mp3/0{i}.jpg", UriKind.RelativeOrAbsolute));
                item.ApplyDisplayProperties(displayProperty);

                PlaybackList.Add(new MediaPlaybackItemDataWrapper(item));
                MediaPlaybackList.Items.Add(item);
            }
        }
Ejemplo n.º 24
0
        private MediaPlaybackItem ToPlaybackItem(Song song)
        {
            var source = MediaSource.CreateFromUri(new Uri(song.StreamUrl));

            var playbackItem = new MediaPlaybackItem(source);

            var displayProperties = playbackItem.GetDisplayProperties();

            displayProperties.Type = Windows.Media.MediaPlaybackType.Music;
            displayProperties.MusicProperties.Title  = song.Title;
            displayProperties.MusicProperties.Artist = song.Artist;
            displayProperties.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri(song.AlbumArt));

            playbackItem.ApplyDisplayProperties(displayProperties);

            source.CustomProperties[MediaItemIdKey] = song.ItemId;

            return(playbackItem);
        }
Ejemplo n.º 25
0
        private void BuildMediaPlaybackList()
        {
            for (int i = 1; i < 5; i++)
            {
                string file = $"ms-appx:///Assets/mp3/0{i}.mp3";

                MediaSource                source          = MediaSource.CreateFromUri(new Uri(file, UriKind.RelativeOrAbsolute));
                MediaPlaybackItem          item            = new MediaPlaybackItem(source);
                MediaItemDisplayProperties displayProperty = item.GetDisplayProperties();
                displayProperty.Type = MediaPlaybackType.Music;
                displayProperty.MusicProperties.Title       = $"0{i}.mp3";
                displayProperty.MusicProperties.AlbumArtist = "JJ";
                displayProperty.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri($"ms-appx:///Assets/mp3/0{i}.jpg", UriKind.RelativeOrAbsolute));
                item.ApplyDisplayProperties(displayProperty);

                PlaybackList.Add(new MediaPlaybackItemDataWrapper(item));
                MediaPlaybackList.Items.Add(item);
            }
        }
Ejemplo n.º 26
0
        private async void USBMediaPlayer_Loaded(object sender, RoutedEventArgs e)
        {
            if (MediaFile.FileType == ".mp3" || MediaFile.FileType == ".flac" || MediaFile.FileType == ".wma" || MediaFile.FileType == ".m4a" || MediaFile.FileType == ".alac")
            {
                MusicCover.Visibility = Visibility.Visible;

                var Artist = GetMusicCoverAsync();

                MediaPlaybackItem          Item  = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(MediaFile));
                MediaItemDisplayProperties Props = Item.GetDisplayProperties();
                //若为音乐此处必须设定为Music
                Props.Type = Windows.Media.MediaPlaybackType.Music;
                Props.MusicProperties.Title = MediaFile.DisplayName;

                try
                {
                    Props.MusicProperties.AlbumArtist = await Artist;
                }
                catch (Exception)
                {
                    Cover.Visibility = Visibility.Collapsed;
                }
                Item.ApplyDisplayProperties(Props);

                Display.Text     = "请欣赏:" + MediaFile.DisplayName;
                MVControl.Source = Item;
            }
            else
            {
                MusicCover.Visibility = Visibility.Collapsed;

                MediaPlaybackItem          Item  = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(MediaFile));
                MediaItemDisplayProperties Props = Item.GetDisplayProperties();
                //若为视频此处必须设定为Video
                Props.Type = Windows.Media.MediaPlaybackType.Video;
                Props.VideoProperties.Title = MediaFile.DisplayName;
                Item.ApplyDisplayProperties(Props);

                MVControl.Source = Item;
            }
        }
Ejemplo n.º 27
0
        public async Task <List <MediaPlaybackItem> > GetPlayableItems(Album album)
        {
            List <MediaPlaybackItem> res = new List <MediaPlaybackItem>();

            try
            {
                RandomAccessStreamReference thumbnail = null;
                if (album.HasCover)
                {
                    StorageFile thumnailFile = await StorageFile.GetFileFromPathAsync(album.CoverPath);

                    thumbnail = RandomAccessStreamReference.CreateFromFile(thumnailFile);
                }

                foreach (Track track in album.Tracks)
                {
                    StorageFile file = await StorageFile.GetFileFromPathAsync(Path.Combine(Root.Path, track.FilePath));

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

                    MediaItemDisplayProperties props = item.GetDisplayProperties();
                    props.Type = Windows.Media.MediaPlaybackType.Music;
                    props.MusicProperties.Title       = $"{album.Title} - {track.Title}";
                    props.MusicProperties.Artist      = album.Composer;
                    props.MusicProperties.TrackNumber = (uint)track.Number;
                    props.Thumbnail = thumbnail;
                    item.ApplyDisplayProperties(props);
                    res.Add(item);

                    item.Source.CustomProperties.Add("track", track);
                    item.Source.CustomProperties.Add("album", album);
                }
            }
            catch (Exception)
            {
                return(null);
            }

            return(res);
        }
Ejemplo n.º 28
0
        public static async Task <Song> ToSong(this StorageFile file)
        {
            var musicProperties = await file.Properties.GetMusicPropertiesAsync();

            var thumbnail = await file.GetThumbnailAsync(ThumbnailMode.MusicView);

            var source    = MediaSource.CreateFromStorageFile(file);
            var mediaItem = new MediaPlaybackItem(source);

            var displayProperties = mediaItem.GetDisplayProperties();

            displayProperties.Type      = Windows.Media.MediaPlaybackType.Music;
            displayProperties.Thumbnail = RandomAccessStreamReference.CreateFromStream(thumbnail);
            displayProperties.MusicProperties.AlbumArtist = musicProperties.AlbumArtist;
            displayProperties.MusicProperties.AlbumTitle  = musicProperties.Album;
            displayProperties.MusicProperties.TrackNumber = musicProperties.TrackNumber;
            displayProperties.MusicProperties.Title       = musicProperties.Title;
            displayProperties.MusicProperties.Artist      = musicProperties.Artist;

            var song = new Song();

            song.AlbumArtist = musicProperties.AlbumArtist;
            song.Album       = musicProperties.Album;
            song.TrackNumber = musicProperties.TrackNumber;
            song.Title       = musicProperties.Title;
            song.Artist      = musicProperties.Artist;
            foreach (var genre in musicProperties.Genre)
            {
                song.Genres.Add(genre);
                displayProperties.MusicProperties.Genres.Add(genre);
            }

            mediaItem.ApplyDisplayProperties(displayProperties);

            song.PlaybackItem = mediaItem;
            song.AlbumArt     = new BitmapImage();
            await song.AlbumArt.SetSourceAsync(thumbnail);

            return(song);
        }
Ejemplo n.º 29
0
        private void WriteSmtcThumbnail(MediaPlaybackItem item, TrackViewModel track)
        {
            var album = track.Album;

            Observable
            .FromAsync(_ => StorageFile.GetFileFromPathAsync(album.CoverPath).AsTask())
            .Catch((Exception ex) => Observable.FromAsync(_ => StorageFile.GetFileFromApplicationUriAsync(new Uri(album.CoverPath)).AsTask()))
            .FirstAsync()
            .Subscribe(x =>
            {
                var prop                        = item.GetDisplayProperties();
                var rasf                        = RandomAccessStreamReference.CreateFromFile(x);
                prop.Thumbnail                  = rasf;
                prop.Type                       = MediaPlaybackType.Music;
                prop.MusicProperties.Title      = track.Title;
                prop.MusicProperties.Artist     = track.Album.Artist.Name;
                prop.MusicProperties.AlbumTitle = track.Album.Title;

                item.ApplyDisplayProperties(prop);
            },
                       ex => { Debugger.Break(); });
        }
Ejemplo n.º 30
0
        private async void PlayingService_OnPlayingSongChanged()
        {
            ChangeImage();
            ChangePlayBar(PlayingService.PlayingSong, PlayingService.PlayingAlbumBitmapImage, PlayingService.PlayingSong.Name, PlayingService.PlayingSong.ar.First().name, PlayingService.PlayingSong.al.name, PlayingService.PlayingSong.dt / 1000);
            if ((Application.Current as App).playingPage != null)
            {
                (Application.Current as App).playingPage.LoadLayout();
            }
            if ((Application.Current as App).compactOverlayPage != null)
            {
                (Application.Current as App).compactOverlayPage.UpdateLayout();
            }
            if (PlayingService.PlayingSongUrlRoot.data.First().url == null)
            {
                NotifyPopup notifyPopup = new NotifyPopup("播放地址错误");
                notifyPopup.Show();
                //跳过当前到下一首
                PlayingService.PlayNextSongs();
                return;
            }
            _mediaSource = await Task.Run(() => MediaSource.CreateFromUri(new Uri(PlayingService.PlayingSongUrlRoot.data.First().url)));

            _mediaSource.OpenOperationCompleted += _mediaSource_OpenOperationCompleted;
            _mediaPlaybackItem  = new MediaPlaybackItem(_mediaSource);
            _mediaPlayer.Source = _mediaPlaybackItem;
            _mediaTimelineController.Start();
            //SetLastPlayedSong();

            //修改SMTC 显示的元数据

            MediaItemDisplayProperties props = _mediaPlaybackItem.GetDisplayProperties();

            props.Type = Windows.Media.MediaPlaybackType.Music;
            props.MusicProperties.Title  = PlayingService.PlayingSong.Name;
            props.MusicProperties.Artist = PlayingService.PlayingSong.ar.First().name;
            props.Thumbnail = RandomAccessStreamReference.CreateFromFile(await ApplicationData.Current.LocalFolder.TryGetItemAsync(ConfigService.ImageFilename) as StorageFile);
            _mediaPlaybackItem.ApplyDisplayProperties(props);
        }
Ejemplo n.º 31
0
        private async Task Initialize()
        {
            if (MediaFile.FileType == ".mp3" || MediaFile.FileType == ".flac" || MediaFile.FileType == ".wma" || MediaFile.FileType == ".m4a" || MediaFile.FileType == ".alac")
            {
                MusicCover.Visibility = Visibility.Visible;

                MediaPlaybackItem Item = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(MediaFile));

                MediaItemDisplayProperties Props = Item.GetDisplayProperties();
                Props.Type = Windows.Media.MediaPlaybackType.Music;
                Props.MusicProperties.Title = MediaFile.DisplayName;

                try
                {
                    Props.MusicProperties.AlbumArtist = await GetMusicCoverAsync().ConfigureAwait(true);
                }
                catch (Exception)
                {
                    Cover.Visibility = Visibility.Collapsed;
                }
                Item.ApplyDisplayProperties(Props);

                Display.Text     = $"{Globalization.GetString("Media_Tip_Text")} {MediaFile.DisplayName}";
                MVControl.Source = Item;
            }
            else
            {
                MusicCover.Visibility = Visibility.Collapsed;

                MediaPlaybackItem          Item  = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(MediaFile));
                MediaItemDisplayProperties Props = Item.GetDisplayProperties();
                Props.Type = Windows.Media.MediaPlaybackType.Video;
                Props.VideoProperties.Title = MediaFile.DisplayName;
                Item.ApplyDisplayProperties(Props);

                MVControl.Source = Item;
            }
        }
        public virtual MediaPlaybackItem ToPlaybackItem()
        {
            // Create the media source from the Uri
            var source = MediaSource.CreateFromUri(MediaUri);

            // Create a configurable playback item backed by the media source
            var playbackItem = new MediaPlaybackItem(source);

            var displayProperties = playbackItem.GetDisplayProperties();

            // Populate thumbnail
            if (PreviewImageUri != null)
            {
                displayProperties.Thumbnail = RandomAccessStreamReference.CreateFromUri(PreviewImageUri);
            }

            // Apply properties to the playback item
            playbackItem.ApplyDisplayProperties(displayProperties);

            source.CustomProperties[MediaItem.MediaItemIdKey] = ItemId;

            return(playbackItem);
        }