// Media set up

        //------------------------------------------------------------------------------
        //
        // StartPlayback
        //
        // News up a MediaPlayer, creates a playback item then 
        // MediaPlayer hands out a surface that can be put on brush
        // We call this below when we set up the tree init the composition
        //
        //------------------------------------------------------------------------------
        private void StartPlayback()
        {


            // MediaPlayer set up with a create from URI
            _mediaPlayer = new MediaPlayer();

            // Get a source from a URI. This could also be from a file via a picker or a stream

            var source = MediaSource.CreateFromUri(new Uri("http://go.microsoft.com/fwlink/?LinkID=809007&clcid=0x409"));
            var item = new MediaPlaybackItem(source);
            _mediaPlayer.Source = item;

            // MediaPlayer supports many of the starndard MediaElement vars like looping
            _mediaPlayer.IsLoopingEnabled = true;

            // Get the surface from MediaPlayer and put it on a brush
            _videoSurface = _mediaPlayer.GetSurface(_compositor);
            _videoVisual.Brush = _compositor.CreateSurfaceBrush(_videoSurface.CompositionSurface);

            // Play the video on app run.

            PlayVideo();

        }
        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;
        }
        string GetTrackId(MediaPlaybackItem item)
        {
            if (item == null)
                return null; // no track playing

            return item.Source.CustomProperties[TrackIdKey] as string;
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.item = new MediaPlaybackItem(MediaSource.CreateFromUri(rootPage.MultiTrackVideoMediaUri));

            item.VideoTracks.SelectedIndexChanged += VideoTracks_SelectedIndexChanged;

            this.mediaPlayerElement.Source = item;
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            this.item = new MediaPlaybackItem(MediaSource.CreateFromUri(rootPage.CaptionedMediaUri));

            this.mainVideoElement.SetPlaybackSource(item);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            this.item = new MediaPlaybackItem(
                MediaSource.CreateFromUri(
                    new Uri("ms-appx:///Assets/Media/multivideo-with-captions.mkv")));

            this.mainVideoElement.SetPlaybackSource(item);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            this.item = new MediaPlaybackItem(
                MediaSource.CreateFromUri(
                    new Uri("https://mediaplatstorage1.blob.core.windows.net/windows-universal-samples-media/multivideo-with-captions.mkv")));

            this.mainVideoElement.SetPlaybackSource(item);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            this.item = new MediaPlaybackItem(
                MediaSource.CreateFromUri(
                    new Uri("https://mediaplatstorage1.blob.core.windows.net/windows-universal-samples-media/elephantsdream-clip-h264_sd-aac_eng-aac_spa-aac_eng_commentary-srt_eng-srt_por-srt_swe.mkv")));

            this.mainVideoElement.SetPlaybackSource(item);
        }
        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);
            }
        }
        public Scenario3()
        {
            this.InitializeComponent();

            // Create the playback item
            var source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-H264_SD-AAC_eng-AAC_spa-AAC_eng_commentary-SRT_eng-SRT_por-SRT_swe.mkv"));
            var playbackItem = new MediaPlaybackItem(source);

            // Turn on English captions by default
            playbackItem.TimedMetadataTracksChanged += (sender, args) =>
            {
                var changedTrackIndex = args.Index;
                var changedTrack = playbackItem.TimedMetadataTracks[(int)changedTrackIndex];

                if (changedTrack.Language == "eng")
                    playbackItem.TimedMetadataTracks.SetPresentationMode((uint)changedTrackIndex, TimedMetadataTrackPresentationMode.PlatformPresented);
            };
            
            // Set the source to begin playback of the item
            this.mediaElement.SetPlaybackSource(playbackItem);
        }
        public Scenario3()
        {
            this.InitializeComponent();

            // Create the playback item
            var source = MediaSource.CreateFromUri(new Uri("https://mediaplatstorage1.blob.core.windows.net/windows-universal-samples-media/elephantsdream-clip-h264_sd-aac_eng-aac_spa-aac_eng_commentary-srt_eng-srt_por-srt_swe.mkv"));
            var playbackItem = new MediaPlaybackItem(source);

            // Turn on English captions by default
            playbackItem.TimedMetadataTracksChanged += (sender, args) =>
            {
                var changedTrackIndex = args.Index;
                var changedTrack = playbackItem.TimedMetadataTracks[(int)changedTrackIndex];

                if (changedTrack.Language == "eng")
                    playbackItem.TimedMetadataTracks.SetPresentationMode((uint)changedTrackIndex, TimedMetadataTrackPresentationMode.PlatformPresented);
            };
            
            // Set the source to begin playback of the item
            this.mediaElement.SetPlaybackSource(playbackItem);
        }
        public Scenario4()
        {
            this.InitializeComponent();

            // Create the media source and supplement with external timed text sources
            var source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-H264_SD-AAC_eng-AAC_spa-AAC_eng_commentary.mp4"));

            var ttsEnUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-SRT_en.srt");
            var ttsEn = TimedTextSource.CreateFromUri(ttsEnUri);
            ttsMap[ttsEn] = ttsEnUri;

            var ttsPtUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-SRT_pt.srt");
            var ttsPt = TimedTextSource.CreateFromUri(ttsPtUri);
            ttsMap[ttsPt] = ttsPtUri;

            var ttsSvUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-SRT_sv.srt");
            var ttsSv = TimedTextSource.CreateFromUri(ttsSvUri);
            ttsMap[ttsSv] = ttsSvUri;

            ttsEn.Resolved += Tts_Resolved;
            ttsPt.Resolved += Tts_Resolved;
            ttsSv.Resolved += Tts_Resolved;

            source.ExternalTimedTextSources.Add(ttsEn);
            source.ExternalTimedTextSources.Add(ttsPt);
            source.ExternalTimedTextSources.Add(ttsSv);

            // Create the playback item from the source
            var playbackItem = new MediaPlaybackItem(source);

            // Present the first track
            playbackItem.TimedMetadataTracksChanged += (sender, args) =>
            {
                playbackItem.TimedMetadataTracks.SetPresentationMode(0, TimedMetadataTrackPresentationMode.PlatformPresented);
            };
            
            // Set the source to start playback of the item
            this.mediaElement.SetPlaybackSource(playbackItem);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Create the media source and supplement with external timed text sources
            var source = MediaSource.CreateFromUri(rootPage.UncaptionedMediaUri);

            var ttsEnUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-SRT_en.srt");
            var ttsEn = TimedTextSource.CreateFromUri(ttsEnUri);
            ttsMap[ttsEn] = ttsEnUri;

            var ttsPtUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-SRT_pt.srt");
            var ttsPt = TimedTextSource.CreateFromUri(ttsPtUri);
            ttsMap[ttsPt] = ttsPtUri;

            var ttsSvUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-SRT_sv.srt");
            var ttsSv = TimedTextSource.CreateFromUri(ttsSvUri);
            ttsMap[ttsSv] = ttsSvUri;

            ttsEn.Resolved += Tts_Resolved;
            ttsPt.Resolved += Tts_Resolved;
            ttsSv.Resolved += Tts_Resolved;

            source.ExternalTimedTextSources.Add(ttsEn);
            source.ExternalTimedTextSources.Add(ttsPt);
            source.ExternalTimedTextSources.Add(ttsSv);

            // Create the playback item from the source
            var playbackItem = new MediaPlaybackItem(source);

            // Present the first track
            playbackItem.TimedMetadataTracksChanged += (sender, args) =>
            {
                playbackItem.TimedMetadataTracks.SetPresentationMode(0, TimedMetadataTrackPresentationMode.PlatformPresented);
            };

            // Set the source to start playback of the item
            this.mediaElement.SetPlaybackSource(playbackItem);
        }
Exemple #14
0
        /// <summary>
        /// 获取上一次播放的信息
        /// </summary>
        async void GetLastPlayingInfo()
        {
            ChangeImage();
            PlayingService.PlayingAlbumBitmapImage = await FileHelper.ReadLoaclBitmapImage(ConfigService.ImageFilename);

            if (await PlayingService.Load())
            {
                Slider_Volume.Value = PlayingService.Volume * 100;
                if (PlayingService.IsPlayingSong)
                {
                    if (PlayingService.PlayingSong != null)
                    {
                        ChangePlayBar(PlayingService.PlayingSong, PlayingService.PlayingAlbumBitmapImage, PlayingService.PlayingSong.Name, PlayingService.PlayingSong.ar.First().name, PlayingService.PlayingSong.al.name, PlayingService.PlayingSong.dt / 1000, false);
                    }
                }
                else
                {
                    if (PlayingService.PlayingRadio != null)
                    {
                        ChangePlayBar(PlayingService.PlayingAlbumBitmapImage, PlayingService.PlayingRadio.Name, PlayingService.PlayingRadio.Dj.Nickname, PlayingService.PlayingRadio.Name, PlayingService.PlayingRadio.MainSong.Duration / 1000);
                    }
                }
                UpDatePlayOrderStateIcon();
                if (PlayingService.PlayingSongUrlRoot != null)
                {
                    SongUrlRoot songUrlRoot = SongService.GetMusicUrl(PlayingService.PlayingSongUrlRoot.data.First().id);
                    //_mediaSource = await Task.Run(() => MediaSource.CreateFromUri(new Uri(PlayingService.PlayingSongUrlRoot.data.First().url)));
                    _mediaSource = await Task.Run(() => MediaSource.CreateFromUri(new Uri(songUrlRoot.data.First().url)));

                    _mediaSource.OpenOperationCompleted += _mediaSource_OpenOperationCompleted;
                    _mediaSource.StateChanged           += _mediaSource_StateChanged;
                    _mediaPlaybackItem  = new MediaPlaybackItem(_mediaSource);
                    _mediaPlayer.Source = _mediaPlaybackItem;
                }
            }
        }
Exemple #15
0
        private async void PlayingService_OnPlayingRadioChanged()
        {
            ChangeImage();
            ChangePlayBar(PlayingService.PlayingAlbumBitmapImage, PlayingService.PlayingRadio.Name, PlayingService.PlayingRadio.Dj.Nickname, PlayingService.PlayingRadio.Name, PlayingService.PlayingRadio.MainSong.Duration / 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.PlayNextRadio();
                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();

            //修改SMTC 显示的元数据
            MediaItemDisplayProperties props = _mediaPlaybackItem.GetDisplayProperties();

            props.Type = Windows.Media.MediaPlaybackType.Music;
            props.MusicProperties.Title  = PlayingService.PlayingRadio.Name;
            props.MusicProperties.Artist = PlayingService.PlayingRadio.Dj.Nickname;
            props.Thumbnail = RandomAccessStreamReference.CreateFromFile(await ApplicationData.Current.LocalFolder.TryGetItemAsync(ConfigService.ImageFilename) as StorageFile);
            _mediaPlaybackItem.ApplyDisplayProperties(props);
        }
Exemple #16
0
        /// <summary>
        /// When the current song being played changes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public async void CurrentItemChanged(object sender, CurrentMediaPlaybackItemChangedEventArgs e)
        {
            currentlyPlayingItem = e.NewItem;
            if (e.NewItem != null)
            {
                currentSession.SongChanged(e.NewItem);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    if (!App.isInBackgroundMode)
                    {
                        if (Player.SystemMediaTransportControls.DisplayUpdater.Thumbnail != null)
                        {
                            IRandomAccessStreamWithContentType thumbnail = await Player.SystemMediaTransportControls.DisplayUpdater.Thumbnail.OpenReadAsync();
                            BitmapImage bitmapImage = new BitmapImage();
                            bitmapImage.SetSource(thumbnail);
                            App.mainPage.GetPlaybackMenu().SetTrackImage(bitmapImage);
                        }
                        App.mainPage.GetPlaybackMenu().SetTrackName(Player.SystemMediaTransportControls.DisplayUpdater.MusicProperties.Title);
                        App.mainPage.GetPlaybackMenu().SetArtistName(Player.SystemMediaTransportControls.DisplayUpdater.MusicProperties.Artist);
                    }
                });
            }
        }
Exemple #17
0
        public async static Task <MediaPlaybackItem> CreatePlayItemAsync(Uri uri, Uri img, MusicBoardParameter para, string title, string artist, string albumTitle, string albunmArtist)
        {
            var storage = await StorageHelper.FetchLocalMusicBySHA256Async(MHzSongBaseHelper.GetIdentity(para));

            var source = default(MediaSource);

            source = storage != null?MediaSource.CreateFromStorageFile(storage) : MediaSource.CreateFromUri(uri);

            source.CustomProperties["Title"]      = title;
            source.CustomProperties["CheckPoint"] = SetCheckPoint(UTCPoint);
            source.CustomProperties["SHA256"]     = para.SHA256;
            source.CustomProperties["Message"]    = para;
            var item       = new MediaPlaybackItem(source);
            var properties = item.GetDisplayProperties();

            properties.Type                        = Windows.Media.MediaPlaybackType.Music;
            properties.Thumbnail                   = RandomAccessStreamReference.CreateFromUri(img);
            properties.MusicProperties.Title       = title;
            properties.MusicProperties.Artist      = artist;
            properties.MusicProperties.AlbumTitle  = albumTitle;
            properties.MusicProperties.AlbumArtist = albunmArtist;
            item.ApplyDisplayProperties(properties);
            return(item);
        }
Exemple #18
0
 public void SetMediaDisplay(StorageFile file, RandomAccessStreamReference img, string title = default, string subtitle = default)
 {
     try
     {
         MediaPlaybackItem item = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(file))
         {
             AutoLoadedDisplayProperties = AutoLoadedDisplayPropertyKind.MusicOrVideo
         };
         var props = item.GetDisplayProperties();
         props.Type = MediaPlaybackType.Video;
         props.VideoProperties.Title    = title.IsValid() ? title : file.DisplayName;
         props.VideoProperties.Subtitle = subtitle.IsValid() ? subtitle : string.Empty;
         if (img != null)
         {
             props.Thumbnail = img;
         }
         item.ApplyDisplayProperties(props);
         MediaPlayer.Source = item;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemple #19
0
        // </SnippetTextCueEntered>


        #endregion

        #region MediaPlaybackList

        private async void PlayMediaPlaybackList()
        {
            //Create a new picker
            FileOpenPicker filePicker = new FileOpenPicker();

            //Add filetype filters.  In this case wmv and mp4.
            filePicker.FileTypeFilter.Add(".wmv");
            filePicker.FileTypeFilter.Add(".mp4");
            filePicker.FileTypeFilter.Add(".mkv");

            //Set picker start location to the video library
            filePicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;

            // <SnippetPlayMediaPlaybackList>
            StorageFile file = await filePicker.PickSingleFileAsync();

            mediaSource = MediaSource.CreateFromStorageFile(file);
            mediaSource.CustomProperties["Title"] = "Clip 1 title";
            mediaPlaybackItem = new MediaPlaybackItem(mediaSource);


            file = await filePicker.PickSingleFileAsync();

            mediaSource2 = MediaSource.CreateFromStorageFile(file);
            mediaSource2.CustomProperties["Title"] = "Clip 2 title";
            mediaPlaybackItem2 = new MediaPlaybackItem(mediaSource2);

            mediaPlaybackList = new MediaPlaybackList();
            mediaPlaybackList.Items.Add(mediaPlaybackItem);
            mediaPlaybackList.Items.Add(mediaPlaybackItem2);

            mediaPlaybackList.CurrentItemChanged += MediaPlaybackList_CurrentItemChanged;

            mediaElement.SetPlaybackSource(mediaPlaybackList);
            // </SnippetPlayMediaPlaybackList>
        }
Exemple #20
0
        private async Task <int> ReadDirectory(StorageFolder dir, int currentIndex)
        {
            var files = await dir.GetFilesAsync();



            foreach (var file in files)
            {
                if (file.Name.EndsWith(".mp3"))
                {
                    var mediaPlybackItem = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(file));

                    playList.Items.Add(mediaPlybackItem);

                    playlistNames [currentIndex] = file.DisplayName;

                    currentIndex++;
                }

                //appCore.AddFile (file);
            }

            return(currentIndex);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Create the playback item
            var source       = MediaSource.CreateFromUri(rootPage.CaptionedMediaUri);
            var playbackItem = new MediaPlaybackItem(source);

            // Turn on English captions by default
            playbackItem.TimedMetadataTracksChanged += (sender, args) =>
            {
                if (args.CollectionChange == CollectionChange.ItemInserted)
                {
                    uint changedTrackIndex          = args.Index;
                    TimedMetadataTrack changedTrack = playbackItem.TimedMetadataTracks[(int)changedTrackIndex];

                    if (changedTrack.Language == "en")
                    {
                        playbackItem.TimedMetadataTracks.SetPresentationMode(changedTrackIndex, TimedMetadataTrackPresentationMode.PlatformPresented);
                    }
                }
            };

            // Set the source to begin playback of the item
            this.mediaElement.SetPlaybackSource(playbackItem);
        }
        private async Task <MediaPlaybackItem> GetPlayableItem(Track track)
        {
            try
            {
                Album album = track.Album;

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

                    thumbnail = RandomAccessStreamReference.CreateFromFile(thumnailFile);
                }

                StorageFile file = await StorageFile.GetFileFromPathAsync(Path.Combine(libraryService.CurrentLibrary.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.Source.CustomProperties["track"] = track;

                item.ApplyDisplayProperties(props);

                return(item);
            }
            catch (Exception)
            {
                return(null);
            }
        }
        private void RegisterForMediaPlaybackItemEvents(MediaPlaybackItem item)
        {
            // If we encountered some unknown tags in an m3u8 manifest,
            // we might already have metadata tracks in the source,
            // which is used as the constructor for the MediaPlaybackItem,
            // therefore, the MediaPlaybackItem may already have metadata tracks.
            // Since TracksChanged will not be raised for these it is best to check
            // if we have tracks, and set up the handlers:
            if (item.TimedMetadataTracks.Count > 0)
            {
                Log($"Registering existing TimedMetadataTracks, Count: {item.TimedMetadataTracks.Count}");

                for (int index = 0; index < item.TimedMetadataTracks.Count; index++)
                {
                    RegisterMetadataHandlers(item, index);
                }
            }

            // For any tracks found as the content is parsed, we register for the event handler:
            item.TimedMetadataTracksChanged += (MediaPlaybackItem sender, IVectorChangedEventArgs args) =>
            {
                Log($"item.TimedMetadataTracksChanged: CollectionChange:{args.CollectionChange} Index:{args.Index} Total:{sender.TimedMetadataTracks.Count}");

                if (args.CollectionChange == CollectionChange.ItemInserted)
                {
                    RegisterMetadataHandlers(sender, (int)args.Index);
                }
                if (args.CollectionChange == CollectionChange.Reset)
                {
                    for (int index = 0; index < item.TimedMetadataTracks.Count; index++)
                    {
                        RegisterMetadataHandlers(item, index);
                    }
                }
            };
        }
Exemple #24
0
        private async System.Threading.Tasks.Task SetMediaSource()
        {
            //var folderPath = Path.GetDirectoryName(Video.Path);
            var videoFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(Video.Path);

            //var videoFile = await folder.GetFileAsync(Video.FileName);
            if (Video.Markers == null)
            {
                Video.Markers = new List <Markers>();
            }

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                      () =>
            {
                nameLabel.Text = Video.Name;
                mediaPlayer.MediaPlayer.Source = null;
                var mediaPlaybackItem          = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(videoFile));

                mediaPlayer.MediaPlayer.Source = mediaPlaybackItem;
                mediaPlayer.MediaPlayer.PlaybackMediaMarkerReached += MediaPlayer_PlaybackMediaMarkerReached;
                SetMarkers();
            }
                                      ).AsTask();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Create the playback item
            var source = MediaSource.CreateFromUri(rootPage.CaptionedMediaUri);
            var playbackItem = new MediaPlaybackItem(source);

            // Turn on English captions by default
            playbackItem.TimedMetadataTracksChanged += (item, args) =>
            {
                if (args.CollectionChange == CollectionChange.ItemInserted)
                {
                    uint changedTrackIndex = args.Index;
                    TimedMetadataTrack changedTrack = playbackItem.TimedMetadataTracks[(int)changedTrackIndex];

                    if (changedTrack.Language == "en")
                    {
                        playbackItem.TimedMetadataTracks.SetPresentationMode(changedTrackIndex, TimedMetadataTrackPresentationMode.PlatformPresented);
                    }
                }
            };

            // Set the source to begin playback of the item
            this.mediaPlayerElement.Source = playbackItem;
        }
Exemple #26
0
        public async void AddToPlaybackList(List <QueueTrack> queue, int position)
        {
            if (_mediaPlaybackList == null ||
                BackgroundMediaPlayer.Current.Source != _mediaPlaybackList)
            {
                CreatePlaybackList(queue);
            }

            else
            {
                foreach (var item in queue)
                {
                    MediaSource source;
                    if (item.Track.Type == TrackType.Stream || item.Track.AudioLocalUri == null)
                    {
                        source = MediaSource.CreateFromUri(new Uri(item.Track.AudioWebUri));
                    }
                    else
                    {
                        source = MediaSource.CreateFromStorageFile(
                            await StorageHelper.GetFileFromPathAsync(item.Track.AudioLocalUri));
                    }
                    source.Queue(item);
                    var playbackItem = new MediaPlaybackItem(source);

                    if (position > -1 && position < _mediaPlaybackList.Items.Count)
                    {
                        _mediaPlaybackList.Items.Insert(position++, playbackItem);
                    }
                    else
                    {
                        _mediaPlaybackList.Items.Add(playbackItem);
                    }
                }
            }
        }
        /// <summary>
        /// Update Universal Volume Control (UVC) using SystemMediaTransPortControl APIs
        /// </summary>
        private void UpdateUVCOnNewTrack(MediaPlaybackItem item)
        {
            if (item == null)
            {
                smtc.PlaybackStatus = MediaPlaybackStatus.Stopped;
                smtc.DisplayUpdater.MusicProperties.Title = string.Empty;
                smtc.DisplayUpdater.Update();
                return;
            }

            smtc.PlaybackStatus = MediaPlaybackStatus.Playing;
            smtc.DisplayUpdater.Type = MediaPlaybackType.Music;
            smtc.DisplayUpdater.MusicProperties.Title = item.Source.CustomProperties[TitleKey] as string;
            smtc.DisplayUpdater.MusicProperties.Artist = item.Source.CustomProperties[ArtistKey] as string;

            var albumArtUri = item.Source.CustomProperties[AlbumArtKey] as Uri;
            if (albumArtUri != null)
                smtc.DisplayUpdater.Thumbnail = RandomAccessStreamReference.CreateFromUri(albumArtUri);
            else
                smtc.DisplayUpdater.Thumbnail = null;

            smtc.DisplayUpdater.Update();
        }
Exemple #28
0
        /// <summary>
        /// Load the range of tracks from the remote playlist in reverse order
        /// </summary>
        /// <param name="start">The start position on remote to download to local, the last position added to the queue</param>
        /// <param name="end">The end position on remote to download to local, the first position added to the queue</param>
        /// <param name="lockOverride">Whether or not to ignore if the lock is set (Used when recursing into itself)</param>
        /// <returns>True a total of end - start tracks are downloaded, false otherwise</returns>
        public async Task <bool> LoadTracksReverse(int start, int end, bool lockOverride)
        {
            long loadingKey = DateTime.Now.Ticks;

            MainPage.AddLoadingLock(loadingKey);
            if (loadLock && !lockOverride)
            {
                return(false);
            }
            loadLock = true;
            int successes = 0;

            if (start < 0)
            {
                start = 0;
            }
            nextRemoteAttempts.Add(end);
            prevRemoteAttempts.Insert(0, start);

            int limit = end - start + 1;

            App.mainPage.SetLoadingProgress(source, 0, limit, localLock, loadingKey);

            if (localLock != App.playbackService.GlobalLock)
            {
                return(false);
            }

            List <Track> tracks = await GetTracksInRange(start, limit);

            if (tracks.Count != limit)
            {
                UpdateFailuresCount(limit - tracks.Count, loadingKey);
            }
            else
            {
                List <KeyValuePair <MediaSource, Track> > sources = new List <KeyValuePair <MediaSource, Track> >();

                if (this.source == PlaybackSource.Spotify)
                {
                    for (int i = 0; i < tracks.Count; i++)
                    {
                        Track track = tracks[i];
                        if (localLock == App.playbackService.GlobalLock)
                        {
                            if (track.previewUrl != "")
                            {
                                sources.Add(new KeyValuePair <MediaSource, Track>(MediaSource.CreateFromUri(new Uri(track.previewUrl)), track));
                            }
                            else
                            {
                                UpdateFailuresCount(1, loadingKey);
                            }
                        }
                        App.mainPage.SetLoadingProgress(source, i + 1 + limit - tracks.Count, limit, localLock, loadingKey);
                    }
                }
                else if (this.source == PlaybackSource.YouTube && localLock == App.playbackService.GlobalLock)
                {
                    for (int i = 0; i < tracks.Count; i++)
                    {
                        Track track = tracks[i];

                        string videoId = "";
                        if (localLock == App.playbackService.GlobalLock)
                        {
                            videoId = await SearchForVideoId(track);
                        }

                        if (localLock == App.playbackService.GlobalLock)
                        {
                            if (videoId == "")
                            {
                                UpdateFailuresCount(1, loadingKey);
                            }
                            else
                            {
                                try
                                {
                                    sources.Add(new KeyValuePair <MediaSource, Track>(await GetAudioAsync(videoId, track.name), track));
                                }
                                catch (Exception)
                                {
                                    UpdateFailuresCount(1, loadingKey);
                                }
                            }
                        }
                        App.mainPage.SetLoadingProgress(PlaybackSource.YouTube, i + 1 + limit - tracks.Count, limit, localLock, loadingKey);
                    }
                }

                for (int i = sources.Count - 1; i >= 0; i--)
                {
                    KeyValuePair <MediaSource, Track> pair = sources[i];
                    if (localLock == App.playbackService.GlobalLock)
                    {
                        MediaPlaybackItem          playbackItem      = new MediaPlaybackItem(pair.Key);
                        MediaItemDisplayProperties displayProperties = playbackItem.GetDisplayProperties();
                        displayProperties.Type = MediaPlaybackType.Music;
                        displayProperties.MusicProperties.Title      = pair.Value.name;
                        displayProperties.MusicProperties.AlbumTitle = pair.Value.album.name;
                        displayProperties.MusicProperties.Artist     = pair.Value.GetMainArtistName();
                        if (pair.Value.album.imageUrl != "")
                        {
                            displayProperties.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri(pair.Value.album.imageUrl));
                        }
                        playbackItem.ApplyDisplayProperties(displayProperties);
                        pair.Key.CustomProperties["mediaItemId"] = pair.Value.id;

                        string id = GetMediaItemId(playbackItem);
                        if (!playlistMediaIds.Contains(id))
                        {
                            App.playbackService.AddToBeginningOfQueue(playbackItem, localLock);
                            playlistMediaIds.Insert(0, id);
                            successes++;
                        }
                    }
                }
            }

            MainPage.RemoveLoadingLock(loadingKey);

            if (successes != limit && start > 0)
            {
                return(await LoadTracks(start - limit - (limit - tracks.Count), start + limit, true));
            }
            loadLock = false;
            return(tracks.Count == limit);
        }
Exemple #29
0
 public MediaItem(string Url)
 {
     Uri = new Uri(Url);
     MediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromUri(Uri));
 }
        private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
        {
            mediaPlayerElement.MediaPlayer?.DisposeSource();

            AdaptiveMediaSourceCreationResult result = null;
            if (httpClient != null)
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
            }
            else
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
            }
            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                adaptiveMS = result.MediaSource;

                bitrateHelper = new BitrateHelper(adaptiveMS.AvailableBitrates);
                InitializeBitrateLists(adaptiveMS);

                // At this point, we have read the manifest of the media source, and all bitrates are known.
                await UpdatePlaybackBitrate(adaptiveMS.CurrentPlaybackBitrate);
                await UpdateDownloadBitrate(adaptiveMS.CurrentDownloadBitrate);

                // Register for events before resolving the MediaSource.
                RegisterForAdaptiveMediaSourceEvents(adaptiveMS);

                MediaSource source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMS);

                // You can save additional information in the CustomPropertySet for future retrieval.
                // Note: MediaSource.CustomProperties is a ValueSet and therefore can store
                // only serializable types.

                // Save the original Uri.
                source.CustomProperties.Add("uri", uri.ToString());

                // You're likely to put a content tracking id into the CustomProperties.
                source.CustomProperties.Add("contentId", Guid.NewGuid());

                mpItem = new MediaPlaybackItem(source);
            }
            else
            {
                Log("Error creating the AdaptiveMediaSource: " + result.Status);
            }
        }
        private void RegisterMetadataHandlers(MediaPlaybackItem mediaPlaybackItem, int index)
        {
            var timedTrack = mediaPlaybackItem.TimedMetadataTracks[index];
            var contentId = (Guid)mediaPlaybackItem.Source.CustomProperties["contentId"];

            StringBuilder logMsg = new StringBuilder($"{contentId} ");

            if (timedTrack.TrackKind == MediaTrackKind.TimedMetadata &&
                (timedTrack.TimedMetadataKind == TimedMetadataKind.Data ||
                timedTrack.TimedMetadataKind == TimedMetadataKind.Custom))
            {
                // Check for known dispatchTypes:
                var dispatchType = mediaPlaybackItem.TimedMetadataTracks[index].DispatchType;
                if (String.Equals(dispatchType, "EXTM3U", StringComparison.OrdinalIgnoreCase))
                {
                    timedTrack.CueEntered += metadata_extm3u_CueEntered;
                    timedTrack.Label = "HLS Manifest comments";
                    // Tell the platform that the app will render these.
                    // Without this, the CueEntered event will not be raised by the platform.
                    mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented);
                }
                else if (string.Equals(dispatchType, "15260DFFFF49443320FF49443320000F", StringComparison.OrdinalIgnoreCase)) // per Apple TS spec for ID3 meta
                {
                    timedTrack.CueEntered += metadata_id3_CueEntered;
                    timedTrack.Label = "ID3 Tags";
                    mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented);
                }

                // Check for our Custom TimedMetadataTrack
                if (mediaPlaybackItem.TimedMetadataTracks[index].Id == "TrackingEvents")
                {
                    timedTrack.CueEntered += metadata_TrackingEvents_CueEntered;
                    timedTrack.CueExited += metadata_TrackingEvents_CueExited;
                    timedTrack.Label = "Tracking Events";
                    mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented);
                }

                logMsg.AppendLine($"Registered CueEntered for {timedTrack.Label}.");
            }
            else
            {
                logMsg.AppendLine("Did not register CueEntered for TimedMetadataTrack.");
            }
            logMsg.AppendLine($"TimedMetadataKind: {timedTrack.TimedMetadataKind}, Id: {timedTrack.Id}, Label: {timedTrack.Label}, DispatchType: {timedTrack.DispatchType}, Language: {timedTrack.Language}");

            Log(logMsg.ToString());
        }
        private void Item_VideoTracksChanged(MediaPlaybackItem sender, IVectorChangedEventArgs args)
        {
            Log($"item.VideoTracksChanged: CollectionChange:{args.CollectionChange} Index:{args.Index} Total:{sender.VideoTracks.Count}");

            switch (args.CollectionChange)
            {
                case CollectionChange.Reset:
                    foreach (VideoTrack track in sender.VideoTracks)
                    {
                        track.OpenFailed += VideoTrack_OpenFailed;
                    }
                    break;
                case CollectionChange.ItemInserted:
                    VideoTrack newTrack = sender.VideoTracks[(int)args.Index];
                    newTrack.OpenFailed += VideoTrack_OpenFailed;
                    break;
            }
        }
        public static string ToFormattedString(this MediaPlaybackItem item)
        {
            if (item == null)
            {
                return(String.Empty);
            }

            StringBuilder sb = new StringBuilder();

            // MediaPlaybackItem.Source.CustomProperties
            var source = item.Source;

            if (source != null && source.CustomProperties.Any())
            {
                sb.AppendLine();
                sb.AppendLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
                sb.AppendLine("Source.CustomProperties:");
                foreach (var prop in source.CustomProperties)
                {
                    sb.AppendLine(prop.Key + ":\t" + prop.Value);
                }
            }

            // MediaPlaybackItem.VideoTracks[].*
            foreach (var track in item.VideoTracks)
            {
                // Note that AdaptiveMediaSource only exposes a single Video track.  Details on bitrates are directly on the AdaptiveMediaSource.
                sb.AppendLine();
                sb.AppendLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
                sb.AppendLine("TrackKind:\t" + track.TrackKind);
                sb.AppendLine("Id:\t" + track.Id);
                sb.AppendLine("Label:\t" + track.Label);
                sb.AppendLine("Language:\t" + track.Language);
                sb.AppendLine("Name:\t" + track.Name);
                sb.AppendLine("DecoderStatus:\t" + track.SupportInfo.DecoderStatus);
                sb.AppendLine("MediaSourceStatus:\t" + track.SupportInfo.MediaSourceStatus);
                var encodingProps = track.GetEncodingProperties();
                if (encodingProps != null)
                {
                    sb.AppendLine("Encoding Properties:");
                    sb.AppendLine("Type:\t" + encodingProps.Type);
                    sb.AppendLine("Subtype:\t" + MediaFoundationGuidStringExtensions.ToMFAttributeName(encodingProps.Subtype));
                    sb.AppendLine("Bitrate:\t" + encodingProps.Bitrate);
                    sb.AppendLine(encodingProps.FrameRate.ToFormattedString("FrameRate"));
                    sb.AppendLine("Height:\t" + encodingProps.Height);
                    sb.AppendLine(encodingProps.PixelAspectRatio.ToFormattedString("PixelAspectRatio"));
                    sb.AppendLine("ProfileId:\t" + encodingProps.ProfileId);
                    sb.AppendLine("StereoscopicVideoPackingMode:\t" + encodingProps.StereoscopicVideoPackingMode);
                    sb.AppendLine("Width:\t" + encodingProps.Width);
                    var additionalProperties = encodingProps.Properties;
                    sb.AppendLine(additionalProperties.ToFormattedString());
                }
            }

            // MediaPlaybackItem.AudioTracks[].*
            foreach (var track in item.AudioTracks)
            {
                sb.AppendLine();
                sb.AppendLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
                sb.AppendLine("TrackKind:\t" + track.TrackKind);
                sb.AppendLine("Id:\t" + track.Id);
                sb.AppendLine("Label:\t" + track.Label);
                sb.AppendLine("Language:\t" + track.Language);
                sb.AppendLine("Name:\t" + track.Name);
                sb.AppendLine("DecoderStatus:\t" + track.SupportInfo.DecoderStatus);
                sb.AppendLine("MediaSourceStatus:\t" + track.SupportInfo.MediaSourceStatus);
                var encodingProps = track.GetEncodingProperties();
                if (encodingProps != null)
                {
                    sb.AppendLine("Encoding Properties:");
                    sb.AppendLine("Type:\t" + encodingProps.Type);
                    sb.AppendLine("Subtype:\t" + MediaFoundationGuidStringExtensions.ToMFAttributeName(encodingProps.Subtype));
                    sb.AppendLine("Bitrate:\t" + encodingProps.Bitrate);
                    sb.AppendLine("BitsPerSample:\t" + encodingProps.BitsPerSample);
                    sb.AppendLine("ChannelCount:\t" + encodingProps.ChannelCount);
                    sb.AppendLine("SampleRate:\t" + encodingProps.SampleRate);
                    var additionalProperties = encodingProps.Properties;
                    sb.AppendLine(additionalProperties.ToFormattedString());
                }
            }

            // MediaPlaybackItem.TimedMetadataTracks[].*
            foreach (var track in item.TimedMetadataTracks)
            {
                sb.AppendLine();
                sb.AppendLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
                sb.AppendLine("TrackKind:\t" + track.TrackKind);
                sb.AppendLine("Id:\t" + track.Id);
                sb.AppendLine("Label:\t" + track.Label);
                sb.AppendLine("Language:\t" + track.Language);
                sb.AppendLine("Name:\t" + track.Name);
                if (track.ActiveCues != null)
                {
                    sb.AppendLine("ActiveCues.Count:\t" + track.ActiveCues.Count);
                }
                if (track.Cues != null)
                {
                    sb.AppendLine("Cues.Count:\t" + track.Cues.Count);
                }
                sb.AppendLine("DispatchType:\t" + track.DispatchType);
                sb.AppendLine("TimedMetadataKind:\t" + track.TimedMetadataKind);
            }
            return(sb.ToString());
        }
 public MediaModel(StorageFile file)
 {
     MediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(file));
 }
        /// <summary>
        /// Starts playing a given MediaSource. Creates the MediaPlayer if not alreay created, as well
        /// as the CompositionSurfaceBrush that contains the video.
        /// </summary>
        /// <param name="source">The MediaSoruce intended to play on the visual.</param>
        private void LoadSource(MediaSource source)
        {
            EnsureMediaPlayer();

            var item = new MediaPlaybackItem(source);

            _mediaPlayer.Source = item;
            _mediaPlayer.IsLoopingEnabled = true;

            EnsureVideoBrush();

            _mediaPlayer.Play();

            // Now that we have a video selected and playing, its safe to choose an effect.
            if (EffectIndex < 0)
            {
                EffectIndex = 0;
            }
        }
Exemple #36
0
 public PlayingSong(MediaPlaybackItem mediaPlaybackItem, Song song)
 {
     this.MediaPlaybackItem = mediaPlaybackItem;
     this.Song = song;
 }
 public MediaModel(Uri mediaUri)
 {
     MediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromUri(mediaUri));
 }
Exemple #38
0
        private async void FontIcon_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            FontIcon FI = sender as FontIcon;

            AlbumList.SelectedItem = ((FontIcon)sender).DataContext;
            SearchSingleMusic SSM = AlbumCollection[AlbumList.SelectedIndex];

            if (((SolidColorBrush)FI.Foreground).Color == Colors.White)
            {
                string MusicURL = (await NeteaseMusicAPI.GetInstance().GetSongsUrlAsync(AlbumCollection[AlbumList.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);

                var song = await NeteaseMusicAPI.GetInstance().SearchAsync <SingleMusicSearchResult>(SSM.MusicName, 5, 0, NeteaseMusicAPI.SearchType.Song);

                string ImgURL = "";

                foreach (var Song in song.Result.Songs.Where(Song => Song.Name == SSM.MusicName && Song.Al.Name == SSM.Album).Select(Song => Song))
                {
                    ImgURL = Song.Al.PicUrl;
                    break;
                }

                MusicList.ThisPage.FavouriteMusicCollection.Add(new PlayList(SSM.MusicName, SSM.Artist, SSM.Album, SSM.Duration, ImgURL, 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, ImgURL, 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;
                    }
                }
            }
        }
        private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
        {
            if (mediaPlayerElement.MediaPlayer?.Source != null)
            {
                UnregisterHandlers(mediaPlayerElement.MediaPlayer);
                mediaPlayerElement.MediaPlayer.DisposeSource();
            }

            AdaptiveMediaSourceCreationResult result = null;

            if (httpClient != null)
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
            }
            else
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
            }

            // We don't need to save a reference to the MediaSource,
            // because we can obtain it from the MediaPlaybackItem.Source in event handlers.
            MediaSource source;

            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                adaptiveMediaSource = result.MediaSource;

                // At this point, we have read the manifest of the media source, and all bitrates are known.
                bitrateHelper = new BitrateHelper(adaptiveMediaSource.AvailableBitrates);

                // The AdaptiveMediaSource chooses initial playback and download bitrates.
                // See the Tuning scenario for examples of customizing these bitrates.
                await UpdatePlaybackBitrate(adaptiveMediaSource.CurrentPlaybackBitrate);
                await UpdateDownloadBitrateAsync(adaptiveMediaSource.CurrentDownloadBitrate);

                // Register for events before resolving the MediaSource.
                RegisterForAdaptiveMediaSourceEvents(adaptiveMediaSource);

                source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource);
            }
            else
            {
                Log($"Error creating the AdaptiveMediaSource: {result.Status}");

                // Try to load the URI as a progressive download URI.
                Log($"Attempting to create a MediaSource from uri: {uri}");
                source = MediaSource.CreateFromUri(uri);
            }

            // You can save additional information in the CustomPropertySet for future retrieval.
            // Note: MediaSource.CustomProperties is a ValueSet and therefore can store
            // only serializable types.

            // Save the original Uri.
            source.CustomProperties.Add("uri", uri.ToString());

            // You're likely to put a content tracking id into the CustomProperties.
            source.CustomProperties.Add("contentId", Guid.NewGuid());

            RegisterForMediaSourceEvents(source);

            // Register for events before resolving the MediaSource.
            var mpItem = new MediaPlaybackItem(source);

            RegisterForMediaPlaybackItemEvents(mpItem);

            // It is at this point that the MediaSource (within a MediaPlaybackItem) will be fully resolved.
            // It gets opened, and events start being raised.

            // Since we are in an async function, the user may have user navigated away, which will null the MediaPlayer.
            if (mediaPlayerElement.MediaPlayer != null)
            {
                mediaPlayerElement.MediaPlayer.Source = mpItem;
            }
        }
        void InitializePlaybackList()
        {
            // Initialize the playlist data/view model.
            // In a production app your data would be sourced from a data store or service.

            // Add content
            var media1 = new MediaModel();
            media1.Title = "Fitness";
            media1.MediaUri = new Uri("ms-appx:///Assets/Media/multivideo-with-captions.mkv");
            media1.ArtUri = new Uri("ms-appx:///Assets/Media/multivideo.jpg");
            playlistView.Media.Add(media1);

            var media2 = new MediaModel();
            media2.Title = "Elephant's Dream";
            media2.MediaUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-H264_SD-AAC_eng-AAC_spa-AAC_eng_commentary-SRT_eng-SRT_por-SRT_swe.mkv");
            media2.ArtUri = new Uri("ms-appx:///Assets/Media/ElephantsDream.jpg");
            playlistView.Media.Add(media2);

            var media3 = new MediaModel();
            media3.Title = "Sintel";
            media3.MediaUri = new Uri("ms-appx:///Assets/Media/sintel_trailer-480p.mp4");
            media3.ArtUri = new Uri("ms-appx:///Assets/Media/sintel.jpg");
            playlistView.Media.Add(media3);

            // Pre-cache all album art to facilitate smooth gapless transitions.
            // A production app would have a more sophisticated object cache.
            foreach (var media in playlistView.Media)
            {
                var bitmap = new BitmapImage();
                bitmap.UriSource = media.ArtUri;
                artCache[media.ArtUri.ToString()] = bitmap;
            }

            // Initialize the playback list for this content
            foreach(var media in playlistView.Media)
            {
                var mediaSource = MediaSource.CreateFromUri(media.MediaUri);
                mediaSource.CustomProperties["uri"] = media.MediaUri;

                var playbackItem = new MediaPlaybackItem(mediaSource);

                playbackList.Items.Add(playbackItem);
            }

            // Subscribe for changes
            playbackList.CurrentItemChanged += PlaybackList_CurrentItemChanged;

            // Loop
            playbackList.AutoRepeatEnabled = true;
        }
        /// <summary>
        /// Performs all necessary actions (including SystemMediaTransportControls related) of loading a new media item 
        /// in the app for playback.
        /// </summary>
        /// <param name="newItemIndex">index in playlist of new item to load for playback, can be out of range.</param>
        /// <remarks>
        /// If the newItemIndex argument is out of range, it will be adjusted accordingly to stay in range.
        /// </remarks>
        private async Task SetNewMediaItem(int newItemIndex)
        {
            // enable Next button unless we're on last item of the playlist
            if (newItemIndex >= playlist.Count - 1)
            {
                systemMediaControls.IsNextEnabled = false;
                newItemIndex = playlist.Count - 1;
            }
            else
            {
                systemMediaControls.IsNextEnabled = true;
            }

            // enable Previous button unless we're on first item of the playlist
            if (newItemIndex <= 0)
            {
                systemMediaControls.IsPreviousEnabled = false;
                newItemIndex = 0;
            }
            else
            {
                systemMediaControls.IsPreviousEnabled = true;
            }

            // note that the Play, Pause and Stop buttons were already enabled via SetupSystemMediaTransportControls() 
            // invoked during this scenario page's OnNavigateToHandler()


            currentItemIndex = newItemIndex;
            StorageFile mediaFile = playlist[newItemIndex];
            IRandomAccessStream stream = null;
            try
            {
                stream = await mediaFile.OpenAsync(FileAccessMode.Read);
            }
            catch (Exception e)
            {
                // User may have navigated away from this scenario page to another scenario page 
                // before the async operation completed.
                if (isThisPageActive)
                {
                    // If the file can't be opened, for this sample we will behave similar to the case of
                    // setting a corrupted/invalid media file stream on the MediaPlayer (which triggers a 
                    // MediaFailed event).  We abort any ongoing playback by nulling the MediaPlayer's 
                    // source.  The user must press Next or Previous to move to a different media item, 
                    // or use the file picker to load a new set of files to play.
                    mediaPlayer.Source = null;

                    string errorMessage = String.Format(@"Cannot open {0} [""{1}""]." +
                        "\nPress Next or Previous to continue, or select new files to play.",
                        mediaFile.Name,
                        e.Message.Trim());
                    rootPage.NotifyUser(errorMessage, NotifyType.ErrorMessage);
                }
            }

            // User may have navigated away from this scenario page to another scenario page 
            // before the async operation completed. Check to make sure page is still active.
            if (!isThisPageActive)
            {
                return;
            }

            if (stream != null)
            {
                // We're about to change the MediaPlayer's source media, so put ourselves into a 
                // "changing media" state.  We stay in that state until the new media is playing,
                // loaded (if user has currently paused or stopped playback), or failed to load.
                // At those points we will call OnChangingMediaEnded().
                //
                // Note that the SMTC visual state may not update until assigning a source or
                // beginning playback. If using a different API than MediaPlayer, such as AudioGraph,
                // you will need to begin playing a stream to see SMTC update.
                mediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromStream(stream, mediaFile.ContentType));
                mediaPlayer.Source = mediaPlaybackItem;
            }

            try
            {
                // Updates the system UI for media transport controls to display metadata information
                // reflecting the file we are playing (eg. track title, album art/video thumbnail, etc.)
                // We call this even if the mediaFile can't be opened; in that case the method can still 
                // update the system UI to remove any metadata information previously displayed.
                await UpdateSystemMediaControlsDisplayAsync(mediaFile);
            }
            catch (Exception e)
            {
                // Check isThisPageActive as user may have navigated away from this scenario page to 
                // another scenario page before the async operations completed.
                if (isThisPageActive)
                {
                    rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage);
                }
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.item = new MediaPlaybackItem(MediaSource.CreateFromUri(rootPage.MultiTrackVideoMediaUri));

            this.mainVideoElement.SetPlaybackSource(item);
        }
        private void Item_AudioTracksChanged(MediaPlaybackItem sender, IVectorChangedEventArgs args)
        {
            Log($"item.AudioTracksChanged: CollectionChange:{args.CollectionChange} Index:{args.Index} Total:{sender.AudioTracks.Count}");

            switch (args.CollectionChange)
            {
                case CollectionChange.Reset:
                    foreach (AudioTrack track in sender.AudioTracks)
                    {
                        // Tracks are added once as a source discovers them in the source media.
                        // This occurs prior to the track media being opened.
                        // Register here so that we can receive the Track.OpenFailed event.
                        track.OpenFailed += AudioTrack_OpenFailed;
                    }
                    break;
                case CollectionChange.ItemInserted:
                    // Additional tracks added after loading the main source should be registered here.
                    AudioTrack newTrack = sender.AudioTracks[(int)args.Index];
                    newTrack.OpenFailed += AudioTrack_OpenFailed;
                    break;
            }
        }
        private void CreateMediaBreaksForItem(MediaPlaybackItem item)
        {
            if (item != null)
            {
                // We have two ads that will be repeated.
                var redSkyUri  = new Uri("http://az29176.vo.msecnd.net/videocontent/RedSky_FoxRiverWisc_GettyImagesRF-499617760_1080_HD_EN-US.mp4");
                var flowersUri = new Uri("http://az29176.vo.msecnd.net/videocontent/CrocusTL_FramePoolRM_688-580-676_1080_HD_EN-US.mp4");

                // One option is to create a separate MediaPlaybackItem for each of your ads.
                // You might choose to do this if each ad needs different reporting information.
                // Another option is to re-use MediaPlaybackItems in different MediaBreaks.
                // This scenario demonstrates both patterns.
                var ad1 = new MediaPlaybackItem(MediaSource.CreateFromUri(redSkyUri));
                ad1.Source.CustomProperties["contentId"]   = "Ad1_ID";
                ad1.Source.CustomProperties["description"] = "Red Sky";
                ad1.Source.CustomProperties["uri"]         = redSkyUri.ToString();
                RegisterForMediaSourceEvents(ad1.Source);
                RegisterForMediaPlaybackItemEvents(ad1);

                var ad2 = new MediaPlaybackItem(MediaSource.CreateFromUri(flowersUri));
                ad2.Source.CustomProperties["contentId"]   = "Ad2_ID";
                ad2.Source.CustomProperties["description"] = "Flowers";
                ad2.Source.CustomProperties["uri"]         = flowersUri.ToString();
                RegisterForMediaSourceEvents(ad2.Source);
                RegisterForMediaPlaybackItemEvents(ad2);

                var ad3 = new MediaPlaybackItem(MediaSource.CreateFromUri(redSkyUri));
                ad3.Source.CustomProperties["contentId"]   = "Ad3_ID";
                ad3.Source.CustomProperties["description"] = "Red Sky 2";
                ad3.Source.CustomProperties["uri"]         = redSkyUri.ToString();
                RegisterForMediaSourceEvents(ad3.Source);
                RegisterForMediaPlaybackItemEvents(ad3);

                // Create a PrerollBreak on your main content.
                if (item.BreakSchedule.PrerollBreak == null)
                {
                    item.BreakSchedule.PrerollBreak = new MediaBreak(MediaBreakInsertionMethod.Interrupt);
                }

                // Add the ads to the PrerollBreak in the order you want them played
                item.BreakSchedule.PrerollBreak.PlaybackList.Items.Add(ad1);
                item.BreakSchedule.PrerollBreak.PlaybackList.Items.Add(ad2);

                // Add the ads to the MidRoll break at 10% into the main content.
                // To do this, we need to wait until the main MediaPlaybackItem is fully loaded by the player
                // so that we know its Duration. This will happen on MediaSource.OpenOperationCompleted.
                item.Source.OpenOperationCompleted += (sender, args) =>
                {
                    var attachedItem = MediaPlaybackItem.FindFromMediaSource(sender);
                    if (sender.Duration.HasValue)
                    {
                        // For live streaming, the duration will be TimeSpan.MaxValue, which won't work for this scenario,
                        // so we'll assume the total duration is 2 minutes for the purpose of ad insertion.
                        bool isLiveMediaSource   = item.Source.AdaptiveMediaSource != null ? item.Source.AdaptiveMediaSource.IsLive : false;
                        long sourceDurationTicks = isLiveMediaSource ? TimeSpan.FromMinutes(2).Ticks : sender.Duration.Value.Ticks;
                        var  positionAt10PercentOfMainContent = TimeSpan.FromTicks(sourceDurationTicks / 10);

                        // If the content is live, then the ad break replaces the streaming content.
                        // If the content is not live, then the content pauses for the ad, and then resumes
                        // after the ad is complete.
                        MediaBreakInsertionMethod insertionMethod = isLiveMediaSource ? MediaBreakInsertionMethod.Replace : MediaBreakInsertionMethod.Interrupt;
                        var midRollBreak = new MediaBreak(insertionMethod, positionAt10PercentOfMainContent);
                        midRollBreak.PlaybackList.Items.Add(ad2);
                        midRollBreak.PlaybackList.Items.Add(ad1);
                        attachedItem.BreakSchedule.InsertMidrollBreak(midRollBreak);
                        Log($"Added MidRoll at {positionAt10PercentOfMainContent}");
                    }
                };

                // Create a PostrollBreak:
                // Note: for Live content, it will only play once the presentation transitions to VOD.
                if (item.BreakSchedule.PostrollBreak == null)
                {
                    item.BreakSchedule.PostrollBreak = new MediaBreak(MediaBreakInsertionMethod.Interrupt);
                }
                // Add the ads to the PostrollBreak in the order you want them played
                item.BreakSchedule.PostrollBreak.PlaybackList.Items.Add(ad3);
            }
        }
        private void Item_TimedMetadataTracksChanged(MediaPlaybackItem sender, IVectorChangedEventArgs args)
        {
            Log($"item.TimedMetadataTracksChanged: CollectionChange:{args.CollectionChange} Index:{args.Index} Total:{sender.TimedMetadataTracks.Count}");

            // This is the proper time to register for timed metadata Events the app cares to consume.
            // See the Metadata scenario for more details.
        }
 public MediaModel(Uri mediaUri)
 {
     MediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromUri(mediaUri));
 }
Exemple #47
0
 public PlaylistEntry GetEntryForMediaPlaybackItem(MediaPlaybackItem playbackItem)
 {
     return(Entries.FirstOrDefault(e => e.AssociatedPlaybackItem == playbackItem));
 }
Exemple #48
0
        private static async void PlaybackList_CurrentItemChanged(MediaPlaybackList sender, CurrentMediaPlaybackItemChangedEventArgs args)
        {
            try
            {
                if (args.NewItem == null)
                {
                    return;
                }

                var currentItem = sender.CurrentItem;
                if (currentItem == null)
                {
                    return;
                }

                CheckPlaylistState(sender);

                syncedItem = playbackList.CurrentItem;

                RestorePosition();

                if (CurrentEntry == null)
                {
                    return;
                }

                Debug.WriteLine("Switched to episode#" + CurrentEntry.Episode.Title);

                if (currentItem.Source.Duration.HasValue)
                {
                    CurrentEntry.Duration = currentItem.Source.Duration.Value.TotalSeconds;
                }
                else
                {
                    CurrentEntry.Duration = 0;
                }

                if (LocalSettings.Instance.VideoPlayback && args.NewItem.VideoTracks.Count > 0)
                {
                    videoPlayInProgess = true;
                    RaiseVideoPlayerEngaged();
                }
                else if (videoPlayInProgess)
                {
                    videoPlayInProgess = false;
                    RaiseVideoPlayerDisengaged();
                }

                // Playback rate
                try
                {
                    Player.PlaybackSession.PlaybackRate = LocalSettings.Instance.PlaySpeed / 100.0;
                }
                catch (Exception)
                {
                    LocalSettings.Instance.PlaySpeed = 100;
                }

                if (!(Application.Current as App).IsInBackground && CurrentEntry != null && CurrentEntry.IsStreaming && NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable && NetworkHelper.Instance.ConnectionInformation.IsInternetOnMeteredConnection && !LocalSettings.Instance.StreamOnMetered)
                {
                    await DispatchManager.RunOnDispatcherAsync(async() =>
                    {
                        Pause(false);
                        await App.MessageAsync(StringsHelper.StreamingIsDisabled);
                    });
                }

                SyncState(Player.PlaybackSession.PlaybackState);
            }
            catch (Exception ex)
            {
                App.TrackException(ex);
                CoreTools.ShowDebugToast(ex.Message, "PlaybackList_CurrentItemChanged");
            }
        }
        private async Task InitializeAsync()
        {
            try
            {
                using (IRandomAccessStream Stream = await MediaFile.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read))
                {
                    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 = await GetArtistAsync();

                        Item.ApplyDisplayProperties(Props);

                        if (await GetMusicCoverAsync() 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;
                    }
                    }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "Could not load media because an exception was threw");

                QueueContentDialog Dialog = new QueueContentDialog
                {
                    Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                    Content         = Globalization.GetString("QueueDialog_CouldNotLoadMedia_Content"),
                    CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                };

                await Dialog.ShowAsync();

                Frame.GoBack();
            }
        }
 public async Task Play(string url, MediaFileType fileType)
 {
     try
     {
         var mediaPlaybackList = new MediaPlaybackList();
         var mediaSource = await CreateMediaSource(url, fileType);
         var item = new MediaPlaybackItem(mediaSource);
         mediaPlaybackList.Items.Add(item);
         _player.Source = mediaPlaybackList;
         _player.Play();
     }
     catch (Exception e)
     {
         MediaFailed?.Invoke(this, new MediaFailedEventArgs("Unable to start playback", e));
     }
 }
Exemple #51
0
        /// <summary>
        /// Load the range of tracks from the remote playlist
        /// </summary>
        /// <param name="start">The first track to load from remote</param>
        /// <param name="end">The last track to load from remote</param>
        /// <param name="lockOverride">Whether or not to ignore if the lock is set (Used when recursing into itself)</param>
        /// <returns>True a total of end - start tracks are downloaded, false otherwise</returns>
        public async Task <bool> LoadTracks(int start, int end, bool lockOverride)
        {
            long loadingKey = DateTime.Now.Ticks;

            MainPage.AddLoadingLock(loadingKey);
            if (loadLock && !lockOverride)
            {
                return(false);
            }
            loadLock = true;
            int successes = 0;
            int limit;

            if (shuffling)
            {
                if (shufflePositionsAvailable.Count == 0)
                {
                    ReFillShufflePositionsAvailable();
                }
                if (shufflePositionsAvailable.Count < end - start)
                {
                    limit = shufflePositionsAvailable.Count;
                }
                else
                {
                    limit = end - start;
                }
            }
            else
            {
                if (totalTracks > 0 && end >= totalTracks)
                {
                    end = totalTracks - 1;
                }
                nextRemoteAttempts.Insert(0, end);
                if (start == 0)
                {
                    prevRemoteAttempts.Add(start + TRACKS_PER_REQUEST);
                }
                else
                {
                    prevRemoteAttempts.Add(start);
                }

                limit = end - start + 1;
            }

            App.mainPage.SetLoadingProgress(source, 0, limit, localLock, loadingKey);

            if (localLock != App.playbackService.GlobalLock)
            {
                return(false);
            }

            List <Track> tracks = new List <Track>();

            if (shuffling)
            {
                tracks = await GetTracksRandom(limit);
            }
            else
            {
                tracks = await GetTracksInRange(start, limit);
            }

            if (tracks.Count == totalTracks)
            {
                limit = totalTracks;
                App.mainPage.SetLoadingProgress(source, 0, limit, localLock, loadingKey);
            }

            if (tracks.Count != limit)
            {
                UpdateFailuresCount(limit - tracks.Count, loadingKey);
            }

            List <KeyValuePair <MediaSource, Track> > sources = new List <KeyValuePair <MediaSource, Track> >();

            if (source == PlaybackSource.Spotify)
            {
                for (int i = 0; i < tracks.Count; i++)
                {
                    Track track = tracks[i];
                    if (localLock == App.playbackService.GlobalLock)
                    {
                        if (track.previewUrl != "")
                        {
                            sources.Add(new KeyValuePair <MediaSource, Track>(MediaSource.CreateFromUri(new Uri(track.previewUrl)), track));
                        }
                        else
                        {
                            UpdateFailuresCount(1, loadingKey);
                        }
                    }
                    App.mainPage.SetLoadingProgress(source, i + 1 + limit - tracks.Count, limit, localLock, loadingKey);
                }
            }
            else if (source == PlaybackSource.YouTube && localLock == App.playbackService.GlobalLock)
            {
                for (int i = 0; i < tracks.Count; i++)
                {
                    Track track = tracks[i];

                    string videoId = "";
                    if (localLock == App.playbackService.GlobalLock)
                    {
                        videoId = await SearchForVideoId(track);
                    }

                    if (localLock == App.playbackService.GlobalLock)
                    {
                        if (videoId == "")
                        {
                            UpdateFailuresCount(1, loadingKey);
                        }
                        else
                        {
                            try
                            {
                                sources.Add(new KeyValuePair <MediaSource, Track>(await GetAudioAsync(videoId, track.name), track));
                            }
                            catch (Exception)
                            {
                                UpdateFailuresCount(1, loadingKey);
                            }
                        }
                    }
                    App.mainPage.SetLoadingProgress(PlaybackSource.YouTube, i + 1 + limit - tracks.Count, limit, localLock, loadingKey);
                }
            }

            bool firstPlay = false;

            for (int i = 0; i < sources.Count; i++)
            {
                KeyValuePair <MediaSource, Track> pair = sources[i];
                if (localLock == App.playbackService.GlobalLock)
                {
                    MediaPlaybackItem          playbackItem      = new MediaPlaybackItem(pair.Key);
                    MediaItemDisplayProperties displayProperties = playbackItem.GetDisplayProperties();
                    displayProperties.Type = MediaPlaybackType.Music;
                    displayProperties.MusicProperties.Title      = pair.Value.name;
                    displayProperties.MusicProperties.AlbumTitle = pair.Value.album.name;
                    displayProperties.MusicProperties.Artist     = pair.Value.GetMainArtistName();
                    if (pair.Value.album.imageUrl != "")
                    {
                        displayProperties.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri(pair.Value.album.imageUrl));
                    }
                    playbackItem.ApplyDisplayProperties(displayProperties);
                    pair.Key.CustomProperties["mediaItemId"] = pair.Value.id;

                    string id = GetMediaItemId(playbackItem);
                    if (!playlistMediaIds.Contains(id))
                    {
                        App.playbackService.AddToQueue(playbackItem, localLock);
                        playlistMediaIds.Add(id);
                        successes++;
                    }

                    if (currentlyPlaying == "")
                    {
                        firstPlay        = true;
                        currentlyPlaying = GetMediaItemId(playbackItem);
                    }
                }
            }

            if (firstPlay)
            {
                App.playbackService.PlayFromBeginning(localLock);
            }

            MainPage.RemoveLoadingLock(loadingKey);

            if (shuffling)
            {
                if (successes != limit && shufflePositionsAvailable.Count > 0)
                {
                    return(await LoadTracks(0, limit - successes, true));
                }
            }
            else
            {
                if (successes != limit && end < totalTracks - 1)
                {
                    return(await LoadTracks(start + limit, start + limit + (limit - tracks.Count), true));
                }
            }

            loadLock = false;
            return(tracks.Count == limit);
        }
        private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
        {
            if (mediaPlayerElement.MediaPlayer?.Source != null)
            {
                UnregisterHandlers(mediaPlayerElement.MediaPlayer);
                mediaPlayerElement.MediaPlayer.DisposeSource();
            }

            AdaptiveMediaSourceCreationResult result = null;
            if (httpClient != null)
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
            }
            else
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
            }

            // We don't need to save a reference to the MediaSource,
            // because we can obtain it from the MediaPlaybackItem.Source in event handlers.
            MediaSource source;

            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                adaptiveMediaSource = result.MediaSource;

                // At this point, we have read the manifest of the media source, and all bitrates are known.
                bitrateHelper = new BitrateHelper(adaptiveMediaSource.AvailableBitrates);

                // The AdaptiveMediaSource chooses initial playback and download bitrates.
                // See the Tuning scenario for examples of customizing these bitrates.
                await UpdatePlaybackBitrate(adaptiveMediaSource.CurrentPlaybackBitrate);
                await UpdateDownloadBitrateAsync(adaptiveMediaSource.CurrentDownloadBitrate);

                // Register for events before resolving the MediaSource.
                RegisterForAdaptiveMediaSourceEvents(adaptiveMediaSource);

                source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource);
            }
            else
            {
                Log($"Error creating the AdaptiveMediaSource: {result.Status}");

                // Try to load the URI as a progressive download URI.
                Log($"Attempting to create a MediaSource from uri: {uri}");
                source = MediaSource.CreateFromUri(uri);
            }

            // You can save additional information in the CustomPropertySet for future retrieval.
            // Note: MediaSource.CustomProperties is a ValueSet and therefore can store
            // only serializable types.

            // Save the original Uri.
            source.CustomProperties.Add("uri", uri.ToString());

            // You're likely to put a content tracking id into the CustomProperties.
            source.CustomProperties.Add("contentId", Guid.NewGuid());

            RegisterForMediaSourceEvents(source);

            // Register for events before resolving the MediaSource.
            var mpItem = new MediaPlaybackItem(source);
            RegisterForMediaPlaybackItemEvents(mpItem);

            // It is at this point that the MediaSource (within a MediaPlaybackItem) will be fully resolved.
            // It gets opened, and events start being raised.

            // Since we are in an async function, the user may have user navigated away, which will null the MediaPlayer.
            if (mediaPlayerElement.MediaPlayer != null)
            {
                mediaPlayerElement.MediaPlayer.Source = mpItem;
            }
        }
Exemple #53
0
        /// <summary>
        /// When the queue moves to another song
        /// </summary>
        /// <param name="newItem">The new song being played</param>
        public async void SongChanged(MediaPlaybackItem newItem)
        {
            if (firstSongChange)
            {
                firstSongChange = false;
                return;
            }
            else if (totalTracks >= INITIAL_TRACKS_REQUEST + 1)
            {
                string newId = GetMediaItemId(newItem);
                int    index = playlistMediaIds.IndexOf(newId);

                if (index == -1)
                {
                    return;
                }

                currentlyPlaying = newId;

                if (shuffling)
                {
                    // towards end of local tracks and more to load remote
                    if (index >= playlistMediaIds.Count - BUFFER_FROM_LOAD && shufflePositionsAvailable.Count > 0)
                    {
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                        {
                            bool success = await LoadTracks(0, TRACKS_PER_REQUEST);
                            if (success && index > BUFFER_FROM_LOAD)
                            {
                                int deleteUpTo = index - BUFFER_FROM_LOAD;
                                for (int i = 0; i < deleteUpTo; i++)
                                {
                                    App.playbackService.RemoveFromQueue(playlistMediaIds.First(), localLock);
                                    if (playlistMediaIds.Count > 0)
                                    {
                                        playlistMediaIds.RemoveAt(0);
                                    }
                                }
                            }
                        });
                    }
                    // toward end of local tracks and no more ahead on remote, go back to beginning
                    else if (index >= playlistMediaIds.Count - BUFFER_FROM_LOAD && App.playbackService.queue.AutoRepeatEnabled && shufflePositionsAvailable.Count == 0)
                    {
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                        {
                            bool success = await LoadTracks(0, TRACKS_PER_REQUEST - 1);
                            if (success && index > BUFFER_FROM_LOAD)
                            {
                                int deleteUpTo = index - BUFFER_FROM_LOAD;
                                for (int i = 0; i < deleteUpTo; i++)
                                {
                                    App.playbackService.RemoveFromQueue(playlistMediaIds.First(), localLock);
                                    if (playlistMediaIds.Count > 0)
                                    {
                                        playlistMediaIds.RemoveAt(0);
                                    }
                                }
                            }
                        });
                    }
                    // towards end of local tracks and no more ahead on remote and not repeating
                    else if (index >= playlistMediaIds.Count - BUFFER_FROM_LOAD && !App.playbackService.queue.AutoRepeatEnabled && shufflePositionsAvailable.Count == 0)
                    {
                        repeatOnShuffleMarker = true;
                    }
                    // towards beginning of local tracks and more to load remote
                    else if (index < BUFFER_FROM_LOAD && shufflePositionsAvailable.Count < totalTracks - INITIAL_TRACKS_REQUEST && !repeatOnShuffleMarker)
                    {
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                        {
                            bool success = await LoadTracksReverse(0, TRACKS_PER_REQUEST);
                            if (success && index < BUFFER_FROM_LOAD)
                            {
                                int deleteUpTo = playlistMediaIds.Count - BUFFER_FROM_LOAD - 1;
                                for (int i = playlistMediaIds.Count - 1; i > deleteUpTo; i--)
                                {
                                    App.playbackService.RemoveFromQueue(playlistMediaIds.Last(), localLock);
                                    playlistMediaIds.RemoveAt(playlistMediaIds.Count - 1);
                                }
                            }
                        });
                    }
                }
                else
                {
                    int indexToLoadNext = nextRemoteAttempts[0];
                    int indexToLoadPrev = prevRemoteAttempts[0];

                    // towards end of local tracks and more to load remote
                    if (index >= playlistMediaIds.Count - BUFFER_FROM_LOAD && indexToLoadNext < totalTracks - 1)
                    {
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                        {
                            bool success = await LoadTracks(indexToLoadNext + 1, indexToLoadNext + TRACKS_PER_REQUEST);
                            if (success && index > BUFFER_FROM_LOAD)
                            {
                                if (prevRemoteAttempts.Count > 0)
                                {
                                    prevRemoteAttempts.RemoveAt(0);
                                }
                                int deleteUpTo = index - BUFFER_FROM_LOAD;
                                for (int i = 0; i < deleteUpTo; i++)
                                {
                                    App.playbackService.RemoveFromQueue(playlistMediaIds.First(), localLock);
                                    if (playlistMediaIds.Count > 0)
                                    {
                                        playlistMediaIds.RemoveAt(0);
                                    }
                                }
                            }
                        }
                                                                                      );
                    }
                    // toward end of local tracks and no more ahead on remote, go back to beginning
                    else if (index >= playlistMediaIds.Count - BUFFER_FROM_LOAD && App.playbackService.queue.AutoRepeatEnabled && indexToLoadNext >= totalTracks - 1)
                    {
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                        {
                            bool success = await LoadTracks(0, TRACKS_PER_REQUEST - 1);
                            if (success && index > BUFFER_FROM_LOAD)
                            {
                                if (prevRemoteAttempts.Count > 0)
                                {
                                    prevRemoteAttempts.RemoveAt(0);
                                }
                                int deleteUpTo = index - BUFFER_FROM_LOAD;
                                for (int i = 0; i < deleteUpTo; i++)
                                {
                                    App.playbackService.RemoveFromQueue(playlistMediaIds.First(), localLock);
                                    if (playlistMediaIds.Count > 0)
                                    {
                                        playlistMediaIds.RemoveAt(0);
                                    }
                                }
                            }
                        });
                    }
                    // towards beginning of local tracks and more to load remote
                    else if (index < BUFFER_FROM_LOAD && indexToLoadPrev != 0)
                    {
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                        {
                            bool success = await LoadTracksReverse(indexToLoadPrev - TRACKS_PER_REQUEST, indexToLoadPrev - 1);
                            if (success && index < BUFFER_FROM_LOAD)
                            {
                                if (nextRemoteAttempts.Count > 0)
                                {
                                    nextRemoteAttempts.RemoveAt(0);
                                }
                                int deleteUpTo = playlistMediaIds.Count - BUFFER_FROM_LOAD - 1;
                                for (int i = playlistMediaIds.Count - 1; i > deleteUpTo; i--)
                                {
                                    App.playbackService.RemoveFromQueue(playlistMediaIds.Last(), localLock);
                                    playlistMediaIds.RemoveAt(playlistMediaIds.Count - 1);
                                }
                            }
                        });
                    }
                }
            }
        }
 private void RegisterForMediaPlaybackItemEvents(MediaPlaybackItem item)
 {
     item.AudioTracks.SelectedIndexChanged += AudioTracks_SelectedIndexChanged;
     item.AudioTracksChanged += Item_AudioTracksChanged;
     item.VideoTracksChanged += Item_VideoTracksChanged;
     item.TimedMetadataTracksChanged += Item_TimedMetadataTracksChanged;
 }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.item = new MediaPlaybackItem(MediaSource.CreateFromUri(rootPage.MultiTrackVideoMediaUri));

            this.mainVideoElement.SetPlaybackSource(item);
        }
 private void UnregisterForMediaPlaybackItemEvents(MediaPlaybackItem item)
 {
     if (item == null)
     {
         return;
     }
     item.AudioTracks.SelectedIndexChanged -= AudioTracks_SelectedIndexChanged;
     item.AudioTracksChanged -= Item_AudioTracksChanged;
     item.VideoTracksChanged -= Item_VideoTracksChanged;
     item.TimedMetadataTracksChanged -= Item_TimedMetadataTracksChanged;
     foreach (AudioTrack audioTrack in item.AudioTracks)
     {
         audioTrack.OpenFailed -= AudioTrack_OpenFailed;
     }
     foreach (VideoTrack videoTrack in item.VideoTracks)
     {
         videoTrack.OpenFailed -= VideoTrack_OpenFailed;
     }
 }
Exemple #57
0
        private async Task <MediaPlaybackItem> LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
        {
            UnregisterHandlers(mediaPlayerElement.MediaPlayer);
            mediaPlayerElement.MediaPlayer?.DisposeSource();

            AdaptiveMediaSourceCreationResult result = null;

            if (httpClient != null)
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
            }
            else
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
            }

            MediaSource source;

            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                var adaptiveMediaSource = result.MediaSource;

                // We use a helper class that logs all the events for the AdaptiveMediaSource:
                adaptiveMediaSourceLogger = new AdaptiveMediaSourceLogger(LoggerControl, adaptiveMediaSource);

                source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource);
            }
            else
            {
                Log($"Error creating the AdaptiveMediaSource. Status: {result.Status}, ExtendedError.Message: {result.ExtendedError.Message}, ExtendedError.HResult: {result.ExtendedError.HResult.ToString("X8")}");
                return(null);
            }

            // We use a helper class that logs all the events for the MediaSource:
            mediaSourceLogger = new MediaSourceLogger(LoggerControl, source);

            // Save the original Uri.
            source.CustomProperties["uri"] = uri.ToString();

            // You're likely to put a content tracking id into the CustomProperties.
            source.CustomProperties["contentId"] = "MainContent_ID";

            // In addition to logging, this scenario uses MediaSource events:
            RegisterForMediaSourceEvents(source);

            var mpItem = new MediaPlaybackItem(source);

            // We use a helper class that logs all the events for the MediaPlaybackItem:
            mediaPlaybackItemLogger = new MediaPlaybackItemLogger(LoggerControl, mpItem);

            // In addition to logging, this scenario uses MediaPlaybackItem events:
            RegisterForMediaPlaybackItemEvents(mpItem);

            // Now that we should have a MediaPlaybackItem, we will insert pre- mid- and post-roll ads
            // with the MediaBreak API.
            CreateMediaBreaksForItem(mpItem);

            HideDescriptionOnSmallScreen();

            return(mpItem);
        }
 private void RegisterForMediaPlaybackItemEvents(MediaPlaybackItem item)
 {
     item.AudioTracks.SelectedIndexChanged += AudioTracks_SelectedIndexChanged;
     item.AudioTracksChanged         += Item_AudioTracksChanged;
     item.TimedMetadataTracksChanged += Item_TimedMetadataTracksChanged;
 }
 public async Task Play(string url, MediaFileType fileType)
 {
     _loadMediaTaskCompletionSource = new TaskCompletionSource<bool>();
     try
     {
         if (_currentMediaSource != null)
         {
             _currentMediaSource.StateChanged -= MediaSourceOnStateChanged;
             _currentMediaSource.OpenOperationCompleted -= MediaSourceOnOpenOperationCompleted;
         }
         // Todo: sync this with the playback queue
         var mediaPlaybackList = new MediaPlaybackList();
         _currentMediaSource = await CreateMediaSource(url, fileType);
         _currentMediaSource.StateChanged += MediaSourceOnStateChanged;
         _currentMediaSource.OpenOperationCompleted += MediaSourceOnOpenOperationCompleted;
         var item = new MediaPlaybackItem(_currentMediaSource);
         mediaPlaybackList.Items.Add(item);
         _player.Source = mediaPlaybackList;
         _player.Play();
     }
     catch (Exception)
     {
         Debug.WriteLine("Unable to open url: " + url);
     }
 }
Exemple #60
0
        private async Task <PlayingSong> AddSongInternal(Song song)
        {
            Task                       getCover;
            MediaSource                media;
            List <PlayingSong>         list;
            MediaItemDisplayProperties oldProperties = null;

            if (this.mediaItemLookup.ContainsKey(song))
            {
                list = this.mediaItemLookup[song];
                var oldMedia = list.FirstOrDefault()?.MediaPlaybackItem;
                media = oldMedia?.Source;
                if (media is null) // Async could add list before mediasource is added.
                {
                    media = await LibraryRegistry <MediaSource, Uri> .Get(song.LibraryProvider).GetMediaSource(song.MediaId, default);
                }
                else
                {
                    oldProperties = oldMedia.GetDisplayProperties();
                }
            }
            else
            {
                list = new List <PlayingSong>();
                this.mediaItemLookup.Add(song, list);
                media = await LibraryRegistry <MediaSource, Uri> .Get(song.LibraryProvider).GetMediaSource(song.MediaId, default);
            }
            if (media is null)
            {
                return(null);
            }
            var mediaItem = new MediaPlaybackItem(media);


            var viewModel = new PlayingSong(mediaItem, song);

            this.playbackItemLookup.Add(mediaItem, viewModel);
            list.Add(viewModel);

            if (oldProperties is null)
            {
                var displayProperties = mediaItem.GetDisplayProperties();
                displayProperties.Type = Windows.Media.MediaPlaybackType.Music;
                displayProperties.MusicProperties.AlbumTitle  = song.AlbumName;
                displayProperties.MusicProperties.TrackNumber = (uint)song.Track;
                displayProperties.MusicProperties.Title       = song.Title;

                displayProperties.MusicProperties.Genres.Clear();
                foreach (var genre in song.Genres)
                {
                    displayProperties.MusicProperties.Genres.Add(genre);
                }

                displayProperties.MusicProperties.Artist = string.Join(", ", song.Interpreters);

                mediaItem.ApplyDisplayProperties(displayProperties);

                var coverTask = song.GetCover(300, default);
                getCover = coverTask.ContinueWith(t =>
                {
                    var coverStreamReferance    = t.Result;
                    displayProperties.Thumbnail = coverStreamReferance;
                    mediaItem.ApplyDisplayProperties(displayProperties);
                });
            }
            else
            {
                getCover = null;
            }

            this.mediaPlaybackList.Items.Add(mediaItem);

            int indexAdded;

            if (this.mediaPlaybackList.ShuffleEnabled)
            {
                indexAdded = this.mediaPlaybackList.ShuffledItems.Select((value, index) => (value, index)).First(x => x.value == mediaItem).index;
            }
            else
            {
                indexAdded = this.mediaPlaybackList.Items.Count - 1;
            }

            this.currentPlaylist.Insert(indexAdded, viewModel);

            if (getCover != null)
            {
                await getCover;
            }
            return(viewModel);
        }