public MEncoderCommandBuilder(MediaSource ms)
 {
     _source = ms;
     //this.AudioEncoderFormat = MEncoder.AudioFormat.LAVC;
     this.AudioEncoderFormat = MEncoder.AudioFormat.Copy;
     this.VideoEncoderFormat = ms.Subtitle == null ? MEncoder.VideoFormat.Copy : MEncoder.VideoFormat.LAVC;
 }
Ejemplo n.º 2
0
        public MoviePlayerWVX(MediaSource source)
        {
            _mItem = source;

            OMLApplication.DebugLine("[MoviePlayerWVX] Loading for playlist: " + _mItem.MediaPath);
            _wplm = new WVXManager(_mItem.MediaPath);
            _currentItem = 0;
        }
    public void GetHashCode_Method()
    {
      var source = new MediaSource("url", "contentType");

      Assert.True(source.GetHashCode() != new object().GetHashCode());
      Assert.True(source.GetHashCode() != new MediaSource("newUrl", "contentType").GetHashCode());
      Assert.Equal(source.GetHashCode(), source.GetHashCode());
      Assert.Equal(new MediaSource("url", "newContentType").GetHashCode(), source.GetHashCode());
    }
        public static bool CanPlay(MediaSource source)
        {
            return true;
            //if (FindMPeg(source) != null)
            //    return true;

            //// TODO: allow to play auto-merging VOBs, asx, and other handings below
            //return false;
        }
    public void ContentType_Property()
    {
      Assert.Throws<ArgumentNullException>(() => new MediaSource("url", null));
      Assert.Throws<ArgumentException>(() => new MediaSource("url", string.Empty));

      var source = new MediaSource("url", "contentType");
      source.ContentType = VideoContentTypes.Flash;
      Assert.Equal(VideoContentTypes.Flash, source.ContentType);
    }
        public TranscodingAPI(MediaSource source, TranscodingStatusChanged action)
        {
            Source = source;
            _Action = action;
            Status = TranscodingStatus.Unknown;

            TranscodingNotifyingService.Start();
            TranscodingNotifyingService.OnMediaSourceStatusChanged += TranscodingNotifyingService_OnMediaSourceStatusChanged;
        }
    public void Url_Property()
    {
      Assert.Throws<ArgumentNullException>(() => new MediaSource(null, "contentType"));
      Assert.Throws<ArgumentException>(() => new MediaSource(string.Empty, "contentType"));

      var source = new MediaSource("url", "contentType");
      source.Url = "http://yandex.ru";
      Assert.Equal("http://yandex.ru", source.Url);
    }
    public void Equals_Methods()
    {
      var source = new MediaSource("url", "contentType");

      Assert.False(source.Equals(null));
      Assert.False(source.Equals(new object()));
      Assert.False(source.Equals(new MediaSource("newUrl", "contentType")));
      Assert.True(source.Equals(source));
      Assert.True(source.Equals(new MediaSource("url", "newContentType")));
    }
    public void Constructors()
    {
      Assert.Throws<ArgumentNullException>(() => new MediaSource(null, "contentType"));
      Assert.Throws<ArgumentNullException>(() => new MediaSource("url", null));
      Assert.Throws<ArgumentException>(() => new MediaSource(string.Empty, "contentType"));
      Assert.Throws<ArgumentException>(() => new MediaSource("url", string.Empty));

      var source = new MediaSource("url", "contentType");
      Assert.Equal("url", source.Url);
      Assert.Equal("contentType", source.ContentType);
    }
Ejemplo n.º 10
0
        public Transcode(MediaSource source)
        {
            Source = source;
            FileInfo file = new FileInfo(source.GetTranscodingFileName());
            if (file.Exists)
            {
                file.Delete();
                _stream = File.Open(file.FullName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            }

            _mencoderlogname = source.GetTranscodingFileName() + ".log";
            _mencoderloglevel = MEncoderLogging.All; //.InfoOnly;
        }
Ejemplo n.º 11
0
 public static void PlayMedia(MediaElement mediaElement, MediaSource mediaSource)
 {
     try
     {
         if (mediaSource != null && mediaSource.Uri != null)
         {
             mediaElement.Stop();
             mediaElement.Source = mediaSource.Uri;
             mediaElement.Play();
         }
     }
     catch (Exception ex)
     {
         Logger.TraceEvent(System.Diagnostics.TraceEventType.Error, "ManagerConsole.Helper.MediaManager:.\r\n{0}", ex.ToString());
     }
 }
Ejemplo n.º 12
0
        public static void PlayMedia(MediaElement mediaElement, MediaSource mediaSource)
        {
            try
            {
                if (mediaSource != null && mediaSource.Uri != null)
                {
                    mediaElement.Stop();
                    mediaElement.Source = mediaSource.Uri;
                    mediaElement.Play();
                }
            }
            catch (Exception ex)
            {

            }
        }
        public void TEST_BASIC_COMMAND_BUILDER()
        {
            string drive = OMLSettings.VirtualDiscDrive.ToLower();
            MediaSource ms = new MediaSource(new Disk("", drive + ":", VideoFormat.DVD));
            MEncoderCommandBuilder builder = new MEncoderCommandBuilder(ms)
            {
                AudioEncoderFormat = MEncoder.AudioFormat.Copy,
                VideoEncoderFormat = MEncoder.VideoFormat.Copy,
            };

            Assert.IsNotNull(builder.GetArguments(MEncoderLogging.None));
            Assert.AreEqual(@" dvd:// -dvd-device """ + drive.ToLower() +
                            @":\"" -oac copy -ovc copy -of mpeg -mpegopts format=dvd:tsaf " +
                            @"-vf harddup -really-quiet -o """ + FileSystemWalker.TranscodeBufferDirectory.ToLower() + @"\mymovie.mpg""", builder.GetArguments(MEncoderLogging.None).ToLower());
            Assert.IsNotNull(builder.GetCommand());
            Assert.AreEqual(Path.GetFullPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)) + @"\openmedialibrary\mencoder.exe", builder.GetCommand().ToLower());
        }
        /// <summary>
        /// Creates a TimedMetadataTrack on the source
        /// </summary>
        /// <param name="source">the source on which to create a TimedMetadataTrack</param>
        /// <param name="contentId">the content id for this source</param>
        /// <param name="reportingUriFormat">the format string used to create reporting Uri for each event</param>
        public static void CreateTrackingEventsTrack(MediaSource source, string contentId, string reportingUriFormat)
        {
            if (source.Duration.HasValue && !string.IsNullOrEmpty(contentId))
            {
                long sourceDurationTicks = source.Duration.Value.Ticks;
                sourceDurationTicks = AdjustDurationIfLive(sourceDurationTicks);

                var trackingEvents = new TimedMetadataTrack("TrackingEvents", "", TimedMetadataKind.Custom);
                trackingEvents.AddCue(new TrackingEventCue()
                {
                    // This method is called once the media has loaded. If it is set to AutoPlay, then
                    // we may miss Position=0.0. Avoid the race by "starting" at the 2-second mark.
                    StartTime = TimeSpan.FromSeconds(2),
                    Id = "2s",
                    TrackingEventUri = new Uri(string.Format(reportingUriFormat, "started", contentId)),
                });
                trackingEvents.AddCue(new TrackingEventCue()
                {
                    StartTime = TimeSpan.FromTicks((long)Math.Round(sourceDurationTicks * 0.25)),
                    Id = "0.25",
                    TrackingEventUri = new Uri(string.Format(reportingUriFormat, "firstQuartile", contentId)),
                });
                trackingEvents.AddCue(new TrackingEventCue()
                {
                    StartTime = TimeSpan.FromTicks((long)Math.Round(sourceDurationTicks * 0.50)),
                    Id = "0.50",
                    TrackingEventUri = new Uri(string.Format(reportingUriFormat, "midpoint", contentId)),
                    // We can cause CueExited to fire at 55% by setting a Duration:
                    Duration = TimeSpan.FromTicks((long)Math.Round(sourceDurationTicks * 0.05)),
                });
                trackingEvents.AddCue(new TrackingEventCue()
                {
                    StartTime = TimeSpan.FromTicks((long)Math.Round(sourceDurationTicks * 0.75)),
                    Id = "0.75",
                    TrackingEventUri = new Uri(string.Format(reportingUriFormat, "thirdQuartile", contentId)),
                });
                trackingEvents.AddCue(new TrackingEventCue()
                {
                    StartTime = TimeSpan.FromTicks(sourceDurationTicks),
                    Id = "1.00",
                    TrackingEventUri = new Uri(string.Format(reportingUriFormat, "complete", contentId)),
                });
                source.ExternalTimedMetadataTracks.Add(trackingEvents);
            }
        }
 private void Source_StateChanged(MediaSource sender, MediaSourceStateChangedEventArgs args)
 {
     Log($"Source.StateChanged:{args.OldState} to {args.NewState}");
 }
Ejemplo n.º 16
0
 public MediaSourceNative(MediaSource mediaSource) : base(mediaSource)
 {
     _mediaSource = mediaSource;
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Get the MediaSource of the specified youtube video, preferring audio stream to video
        /// </summary>
        /// <param name="videoId">The id of the video to get audio for</param>
        /// <returns>The audio of the track</returns>
        private async Task <MediaSource> GetAudioAsync(string videoId, string trackName)
        {
            IEnumerable <YouTubeVideo> videos = await YouTube.Default.GetAllVideosAsync(string.Format(_videoUrlFormat, videoId));

            YouTubeVideo maxAudioVideo    = null;
            YouTubeVideo maxNonAudioVideo = null;

            try
            {
                for (int i = 0; i < videos.Count(); i++)
                {
                    YouTubeVideo video = videos.ElementAt(i);
                    if (video.AdaptiveKind == AdaptiveKind.Audio)
                    {
                        if (maxAudioVideo == null || video.AudioBitrate > maxAudioVideo.AudioBitrate)
                        {
                            maxAudioVideo = video;
                        }
                    }
                    else
                    {
                        if (maxNonAudioVideo == null || video.AudioBitrate > maxNonAudioVideo.AudioBitrate)
                        {
                            maxNonAudioVideo = video;
                        }
                    }
                }
            }
            catch (HttpRequestException)
            {
                try
                {
                    string url = await videos.ElementAt(0).GetUriAsync();

                    return(MediaSource.CreateFromUri(new Uri(url)));
                }
                catch (Exception)
                {
                    return(MediaSource.CreateFromUri(new Uri("")));
                }
            }
            if (maxAudioVideo != null)
            {
                string url = await maxAudioVideo.GetUriAsync();

                return(MediaSource.CreateFromUri(new Uri(url)));
            }
            else if (maxNonAudioVideo != null)
            {
                HttpClientHandler handler = new HttpClientHandler()
                {
                    AllowAutoRedirect = true
                };
                HttpClient client = new HttpClient(handler);

                CancellationTokenSource cancelToken = new CancellationTokenSource();
                cancelToken.Token.Register(() =>
                {
                    client.CancelPendingRequests();
                    client.Dispose();
                    App.mainPage.HideCancelDialog(localLock);
                });

                try
                {
                    string url = await maxNonAudioVideo.GetUriAsync();

                    Task <HttpResponseMessage> clientTask = client.GetAsync(new Uri(url), HttpCompletionOption.ResponseContentRead, cancelToken.Token);
                    Task completedTask = await Task.WhenAny(clientTask, Task.Delay(5000));

                    if (completedTask != clientTask)
                    {
                        if (App.isInBackgroundMode)
                        {
                            cancelToken.Cancel();
                            return(MediaSource.CreateFromUri(new Uri("")));
                        }
                        else
                        {
                            App.mainPage.ShowCancelDialog(localLock, cancelToken, trackName);
                            await Task.Run(() =>
                            {
                                while ((clientTask.Status == TaskStatus.WaitingForActivation ||
                                        clientTask.Status == TaskStatus.WaitingForChildrenToComplete ||
                                        clientTask.Status == TaskStatus.WaitingToRun ||
                                        clientTask.Status == TaskStatus.Running) && !cancelToken.Token.IsCancellationRequested)
                                {
                                }
                            });

                            App.mainPage.HideCancelDialog(localLock);
                            if (cancelToken.Token.IsCancellationRequested)
                            {
                                return(MediaSource.CreateFromUri(new Uri("")));
                            }
                        }
                    }
                    HttpResponseMessage response = clientTask.Result;
                    Stream stream = await response.Content.ReadAsStreamAsync();

                    return(MediaSource.CreateFromStream(stream.AsRandomAccessStream(), "video/x-flv"));
                }
                catch (OperationCanceledException)
                {
                    return(MediaSource.CreateFromUri(new Uri("")));
                }
            }
            return(MediaSource.CreateFromUri(new Uri("")));
        }
        /// <summary>
        /// Create a topology to be played with a MediaSession from a filepath.
        /// </summary>
        internal static Topology CreateTopology(ByteStream mediaInputStream, out MediaSource mediaSource)
        {
            // collector to dispose all the created Media Foundation native objects.
            var collector = new ObjectCollector();

            // Get the MediaSource object.
            var sourceResolver = new SourceResolver();
            collector.Add(sourceResolver);
            ComObject mediaSourceObject;

            // Try to load music
            try
            {
                mediaSourceObject = sourceResolver.CreateObjectFromStream(mediaInputStream, null, SourceResolverFlags.MediaSource | SourceResolverFlags.ContentDoesNotHaveToMatchExtensionOrMimeType);
            }
            catch (SharpDXException)
            {
                collector.Dispose();
                throw new InvalidOperationException("Music stream format not supported");
            }

            Topology retTopo;

            try
            {
                mediaSource = mediaSourceObject.QueryInterface<MediaSource>();
                collector.Add(mediaSourceObject);

                // Get the PresentationDescriptor
                PresentationDescriptor presDesc;
                mediaSource.CreatePresentationDescriptor(out presDesc);
                collector.Add(presDesc);

                // Create the topology
                MediaFactory.CreateTopology(out retTopo);
                for (var i = 0; i < presDesc.StreamDescriptorCount; i++)
                {
                    Bool selected;
                    StreamDescriptor desc;
                    presDesc.GetStreamDescriptorByIndex(i, out selected, out desc);
                    collector.Add(desc);

                    if (selected)
                    {
                        // Test that the audio file data is valid and supported.
                        var typeHandler = desc.MediaTypeHandler;
                        collector.Add(typeHandler);

                        var majorType = typeHandler.MajorType;

                        if (majorType != MediaTypeGuids.Audio)
                            throw new InvalidOperationException("The music stream is not a valid audio stream.");

                        for (int mType = 0; mType < typeHandler.MediaTypeCount; mType++)
                        {
                            MediaType type;
                            typeHandler.GetMediaTypeByIndex(mType, out type);
                            collector.Add(type);

                            var nbChannels = type.Get(MediaTypeAttributeKeys.AudioNumChannels);
                            if (nbChannels > 2)
                                throw new InvalidOperationException("The provided audio stream has more than 2 channels.");
                        }

                        // create the topology (source,...)
                        TopologyNode sourceNode;
                        MediaFactory.CreateTopologyNode(TopologyType.SourceStreamNode, out sourceNode);
                        collector.Add(sourceNode);

                        sourceNode.Set(TopologyNodeAttributeKeys.Source, mediaSource);
                        sourceNode.Set(TopologyNodeAttributeKeys.PresentationDescriptor, presDesc);
                        sourceNode.Set(TopologyNodeAttributeKeys.StreamDescriptor, desc);

                        TopologyNode outputNode;
                        MediaFactory.CreateTopologyNode(TopologyType.OutputNode, out outputNode);
                        collector.Add(outputNode);

                        Activate activate;
                        MediaFactory.CreateAudioRendererActivate(out activate);
                        collector.Add(activate);
                        outputNode.Object = activate;

                        retTopo.AddNode(sourceNode);
                        retTopo.AddNode(outputNode);
                        sourceNode.ConnectOutput(0, outputNode, 0);
                    }
                }
            }
            finally
            {
                collector.Dispose();
            }

            return retTopo;
        }
Ejemplo n.º 19
0
 public Filter(string name, MediaSource filterType)
 {
     Name        = name ?? throw new ArgumentNullException(nameof(name));
     MediaSource = filterType;
     ID          = Guid.NewGuid();
 }
Ejemplo n.º 20
0
 private void UnregisterForMediaSourceEvents(MediaSource source)
 {
     source.OpenOperationCompleted -= Source_OpenOperationCompleted;
 }
Ejemplo n.º 21
0
        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);
            }
        }
Ejemplo n.º 22
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);
        }
Ejemplo n.º 23
0
 public PostViewModel(ViewModelBase parent, Post post)
 {
     Parent      = parent;
     Post        = post;
     VideoSource = MediaSource.CreateFromUri(post.VideoUri);
 }
Ejemplo n.º 24
0
        public void Play(IEnumerable <MessageViewModel> items, bool auto)
        {
            var news = new Dictionary <long, MediaPlayerItem>();

            foreach (var message in items)
            {
                var container = Messages.ContainerFromItem(message) as ListViewItem;
                if (container == null)
                {
                    continue;
                }

                var animation = message.GetAnimation();
                if (animation == null)
                {
                    continue;
                }

                if (animation.Local.IsDownloadingCompleted)
                {
                    var root = container.ContentTemplateRoot as FrameworkElement;
                    if (root is Grid grid)
                    {
                        root = grid.FindName("Bubble") as FrameworkElement;
                    }

                    var media = root.FindName("Media") as ContentControl;
                    var panel = media.ContentTemplateRoot as Panel;

                    if (message.Content is MessageText)
                    {
                        media = panel.FindName("Media") as ContentControl;
                        panel = media.ContentTemplateRoot as Panel;
                    }
                    else if (message.Content is MessageGame)
                    {
                        panel = panel.FindName("Media") as Panel;
                    }
                    //else if (message.Media is TLMessageMediaGame)
                    //{
                    //    panel = panel.FindName("Media") as FrameworkElement;
                    //}
                    //else if (message.IsRoundVideo())
                    //{
                    //    panel = panel.FindName("Inner") as FrameworkElement;
                    //}

                    if (panel is Grid final)
                    {
                        final.Tag        = message;
                        news[message.Id] = new MediaPlayerItem {
                            File = animation, Container = final, Watermark = message.Content is MessageGame
                        };
                    }
                }
            }

            foreach (var item in _old.Keys.Except(news.Keys).ToList())
            {
                var presenter = _old[item].Presenter;
                if (presenter != null && presenter.MediaPlayer != null)
                {
                    presenter.MediaPlayer.Source = null;
                    presenter.MediaPlayer.Dispose();
                    presenter.MediaPlayer = null;
                }

                var container = _old[item].Container;
                if (container != null && presenter != null)
                {
                    container.Children.Remove(presenter);
                }

                _old.Remove(item);
            }

            if (!auto)
            {
                return;
            }

            foreach (var item in news.Keys.Except(_old.Keys).ToList())
            {
                if (_old.ContainsKey(item))
                {
                    continue;
                }

                var container = news[item].Container;
                if (container != null && container.Children.Count < 5)
                {
                    var player = new MediaPlayer();
                    player.AutoPlay                 = true;
                    player.IsMuted                  = auto;
                    player.IsLoopingEnabled         = true;
                    player.CommandManager.IsEnabled = false;
                    player.Source = MediaSource.CreateFromUri(new Uri("file:///" + news[item].File.Local.Path));

                    var presenter = new MediaPlayerView();
                    presenter.MediaPlayer      = player;
                    presenter.IsHitTestVisible = false;
                    presenter.Constraint       = container.Tag;

                    news[item].Presenter = presenter;
                    //container.Children.Insert(news[item].Watermark ? 2 : 2, presenter);
                    container.Children.Add(presenter);
                }

                _old[item] = news[item];
            }
        }
Ejemplo n.º 25
0
        internal static void ShowFileWarningMessages(string filePath, MediaPathType fileLocation, MediaReference mediaReference, MediaSource mediaSource, bool isAutoOpen, Platform platform)
        {
            MediaPath mediaPath = null;

            if (mediaSource == MediaSource.Path)
            {
                mediaPath = new MediaPath(filePath, fileLocation);
            }
            else if (mediaSource == MediaSource.Reference)
            {
                if (mediaReference != null)
                {
                    mediaPath = mediaReference.GetCurrentPlatformMediaReference().MediaPath;
                }
            }

            ShowFileWarningMessages(mediaPath, isAutoOpen, platform);
        }
Ejemplo n.º 26
0
 public MediaModel(Uri mediaUri)
 {
     MediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromUri(mediaUri));
 }
Ejemplo n.º 27
0
 internal Transcoder(MediaSource source)
 {
     TranscodingProcess = new Transcode(source);
     TranscodingProcess.Exited += TranscodingProcess_Exited;
     Timer = new System.Timers.Timer(1000);
     Timer.AutoReset = true;
     Timer.Elapsed += Timer_Elapsed;
     Timer.Start();
     lock (this)
         Status = TranscodingProcess.BeginTranscodeJob() != 0 ? TranscodingStatus.Error : TranscodingStatus.Initializing;
     TranscodingService.NotifyAll(source.Key, Status);
 }
Ejemplo n.º 28
0
        /**
         * 非同期にソースをロードし、結果をコールバックする
         */
        public static void Load(MediaPlayer player, MediaSource source, DependencyObject ownerView, OnLoadedHandler onLoaded)
        {
            var loader = new WvvMediaLoader(player);

            loader.Load(source, ownerView, onLoaded);
        }
 private void MediaSourceOnOpenOperationCompleted(MediaSource sender,
     MediaSourceOpenOperationCompletedEventArgs args)
 {
     if (args.Error != null)
         MediaFailed?.Invoke(this, new MediaFailedEventArgs(args.Error.ToString(), args.Error.ExtendedError));
 }
Ejemplo n.º 30
0
 public MediaItem(string Url)
 {
     Uri = new Uri(Url);
     MediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromUri(Uri));
 }
Ejemplo n.º 31
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);
        }
Ejemplo n.º 32
0
 public DVDPlayer(MediaSource source, string path)
 {
     _source    = source;
     _mediaPath = path;
 }
Ejemplo n.º 33
0
 public static DbMediaFile Convert(MediaSource value)
 {
     return((DbMediaFile)value.CustomProperties[Light.Core.PlaybackControl.DbMediaFileToken]);
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Creates the source reader from a <see cref="SharpDX.MediaFoundation.MediaSource"/>
 /// </summary>
 /// <param name="source">Reference to the mediasource interface</param>
 /// <param name="attributes"><dd> <p>Pointer to the <strong><see cref="SharpDX.MediaFoundation.MediaAttributes"/></strong> interface. You can use this parameter to configure the source reader. For more information, see Source Reader Attributes. This parameter can be <strong><c>null</c></strong>.</p> </dd></param>
 /// <remarks>
 /// <p>Call <strong>CoInitialize(Ex)</strong> and <strong><see cref="SharpDX.MediaFoundation.MediaFactory.Startup"/></strong> before calling this function.</p><p>By default, when the application releases the source reader, the source reader shuts down the media source by calling <strong><see cref="SharpDX.MediaFoundation.MediaSource.Shutdown"/></strong> on the media source. At that point, the application can no longer use the media source.</p><p>To change this default behavior, set the <see cref="SharpDX.MediaFoundation.SourceReaderAttributeKeys.DisconnectMediasourceOnShutdown"/> attribute in the <em>pAttributes</em> parameter. If this attribute is <strong>TRUE</strong>, the application is responsible for  shutting down the media source.</p><p>When using the Source Reader, do not call any of the following methods on the media source:</p><ul> <li> <strong><see cref="SharpDX.MediaFoundation.MediaSource.Pause"/></strong> </li> <li> <strong><see cref="SharpDX.MediaFoundation.MediaSource.Start"/></strong> </li> <li> <strong><see cref="SharpDX.MediaFoundation.MediaSource.Stop"/></strong> </li> <li>All <strong><see cref="SharpDX.MediaFoundation.MediaEventGenerator"/></strong> methods</li> </ul><p>This function is available on Windows?Vista if Platform Update Supplement for Windows?Vista is installed.</p><p><strong>Windows Phone 8.1:</strong> This API is supported.</p>
 /// </remarks>
 /// <msdn-id>dd388108</msdn-id>
 /// <unmanaged>HRESULT MFCreateSourceReaderFromMediaSource([In] IMFMediaSource* pMediaSource,[In, Optional] IMFAttributes* pAttributes,[Out, Fast] IMFSourceReader** ppSourceReader)</unmanaged>
 /// <unmanaged-short>MFCreateSourceReaderFromMediaSource</unmanaged-short>
 public SourceReader(MediaSource source, MediaAttributes attributes = null)
 {
     MediaFactory.CreateSourceReaderFromMediaSource(source, attributes, this);
 }
Ejemplo n.º 35
0
 public MediaSource GetMediaSource() => MediaSource.CreateFromStorageFile(StorageFile);
Ejemplo n.º 36
0
 /// <summary>
 ///     Play the audio file located at the filePath
 /// </summary>
 /// <param name="filePath"></param>
 public void Play(string filePath, int position)
 {
     mediaPlayer.Source = MediaSource.CreateFromUri(new Uri(filePath));
     mediaPlayer.PlaybackSession.Position = new TimeSpan(0, 0, 0, 0, position);
     mediaPlayer.Play();
 }
 private void UnregisterForMediaSourceEvents(MediaSource source)
 {
     if (source == null)
     {
         return;
     }
     source.StateChanged -= Source_StateChanged;
     source.OpenOperationCompleted -= Source_OpenOperationCompleted;
 }
Ejemplo n.º 38
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     _previewFile         = (StorageFile)e.Parameter;
     PreviewPlayer.Source = MediaSource.CreateFromStorageFile(_previewFile);
 }
        private void Source_OpenOperationCompleted(MediaSource sender, MediaSourceOpenOperationCompletedEventArgs args)
        {
            // Get the MediaPlaybackItem that corresponds to the MediaSource.
            MediaPlaybackItem item = MediaPlaybackItem.FindFromMediaSource(sender);
            if (item != null && item.AudioTracks.Count > 0)
            {
                // The MediaPlaybackItem contains additional information about the underlying media.
                string audioCodec = item.AudioTracks[item.AudioTracks.SelectedIndex].GetEncodingProperties().Subtype;

                // We can read values from the MediaSource.CustomProperties.
                var uri = (string)sender.CustomProperties["uri"];
                var contentId = (Guid)sender.CustomProperties["contentId"];
                Log($"Opened Media Source with Uri: {uri}, ContentId: {contentId}, Codec: {audioCodec}");

                // This extension method in MediaPlaybackItemStringExtensions dumps all the properties from all the tracks.
                var allProperties = item.ToFormattedString();
                Log($"MediaPlaybackItem nested properties: {allProperties}");
                // The AdaptiveMediaSource can manage multiple video tracks internally,
                // but only a single video track is exposed in the MediaPlaybackItem, not a collection.
            }
        }
        void trancoderStatusChanged(MediaSource source, TranscodingStatus status)
        {
            Utilities.DebugLine("[TranscodePlayer] Status Changed: {0}, Status: {1}", _source, status);

            OMLApplication.Current.IsStartingTranscodingJob = true;
            Application.DeferredInvoke(delegate
            {
                switch (status)
                {
                    case TranscodingStatus.Initializing:
                        OMLApplication.DebugLine("Received Transcoding Status Change: Initializing");
                        OMLApplication.Current.IsStartingTranscodingJob = true;
                        OMLApplication.Current.TranscodeStatus = @"Initializing";
                        break;
                    case TranscodingStatus.BufferReady:
                        OMLApplication.DebugLine("Received Transcoding Status Change: Buffer Ready");
                        OMLApplication.Current.IsStartingTranscodingJob = true;
                        OMLApplication.Current.TranscodeStatus = @"Buffer Ready";
                        break;
                    case TranscodingStatus.Done:
                        OMLApplication.DebugLine("Received Transcoding Status Change: Done");
                        OMLApplication.Current.IsStartingTranscodingJob = false;
                        OMLApplication.Current.TranscodeStatus = @"Done";
                        break;
                    case TranscodingStatus.Error:
                        OMLApplication.DebugLine("Received Transcoding Status Change: Error");
                        OMLApplication.Current.IsStartingTranscodingJob = false;
                        OMLApplication.Current.TranscodeStatus = @"Error";
                        break;
                    case TranscodingStatus.Stopped:
                        OMLApplication.DebugLine("Received Transcoding Status Change: Stopped");
                        OMLApplication.Current.IsStartingTranscodingJob = false;
                        OMLApplication.Current.TranscodeStatus = @"Stopped";
                        break;
                    default:
                        OMLApplication.DebugLine("Received Transcoding Status Change: Unknown");
                        break;
                }
            });

            if (OMLApplication.Current.NowPlayingMovieName == _source.Key && OMLApplication.Current.NowPlayingStatus == PlayState.Playing)
            {
                Utilities.DebugLine("[TranscodePlayer] Already started playing: {0}", _source);
                return;
            }

            if (status == TranscodingStatus.Done || status == TranscodingStatus.BufferReady)
            {
                Application.DeferredInvoke(delegate
                {
                    if (AddInHost.Current.MediaCenterEnvironment.PlayMedia(MediaType.Video, transcodedFile, false))
                    {
                        if (AddInHost.Current.MediaCenterEnvironment.MediaExperience != null)
                        {
                            OMLApplication.Current.IsStartingTranscodingJob = false;
                            Utilities.DebugLine("TranscodePlayer.PlayMovie: movie '{0}', Playing file '{1}'", _source.Name, _source.GetTranscodingFileName());
                            OMLApplication.Current.NowPlayingMovieName = _source.Key;
                            OMLApplication.Current.NowPlayingStatus = PlayState.Playing;
                            AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.PropertyChanged -= this.Transport_PropertyChanged;
                            AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.PropertyChanged += this.Transport_PropertyChanged;
                            AddInHost.Current.MediaCenterEnvironment.MediaExperience.GoToFullScreen();
                        }
                    }
                });
            }
        }
    /// <summary>
    /// Setup media dialog from selected item.
    /// </summary>
    /// <param name="selectionTable">Hash table from selected item</param>
    /// <param name="anchorsList">List of anchors from document</param>
    /// <param name="idsList">List of ids from document</param>
    private void SelectMediaDialog(IDictionary selectionTable, ICollection anchorsList, ICollection idsList)
    {
        string insertHeaderLocation = BaseFilePath + "Header.aspx" + RequestContext.CurrentQueryString;

        if (selectionTable.Count > 0)
        {
            string siteName = null;
            string url      = null;
            // If link dialog use only link url
            if (RequestContext.CurrentQueryString.ToLowerCSafe().Contains("link=1"))
            {
                if (selectionTable[DialogParameters.LINK_URL] != null)
                {
                    url = selectionTable[DialogParameters.LINK_URL].ToString();
                    if ((selectionTable[DialogParameters.LINK_PROTOCOL] != null) && (selectionTable[DialogParameters.LINK_PROTOCOL].ToString() != "other"))
                    {
                        // Add protocol only if not already presents
                        if (!url.StartsWithCSafe(selectionTable[DialogParameters.LINK_PROTOCOL].ToString()))
                        {
                            url = selectionTable[DialogParameters.LINK_PROTOCOL] + url;
                        }
                    }
                }
                else if (selectionTable[DialogParameters.URL_URL] != null)
                {
                    url = selectionTable[DialogParameters.URL_URL].ToString();
                }
            }
            else
            {
                // Get url from selection table
                if (selectionTable[DialogParameters.IMG_URL] != null)
                {
                    url = selectionTable[DialogParameters.IMG_URL].ToString();
                }
                else if (selectionTable[DialogParameters.AV_URL] != null)
                {
                    url = selectionTable[DialogParameters.AV_URL].ToString();
                }
                else if (selectionTable[DialogParameters.LINK_URL] != null)
                {
                    url = selectionTable[DialogParameters.LINK_URL].ToString();
                }
                else if (selectionTable[DialogParameters.URL_URL] != null)
                {
                    url      = selectionTable[DialogParameters.URL_URL].ToString();
                    siteName = (selectionTable[DialogParameters.URL_SITENAME] != null ? selectionTable[DialogParameters.URL_SITENAME].ToString() : null);
                }
            }
            string query = URLHelper.RemoveUrlParameter(RequestContext.CurrentQueryString, "hash");

            // Get the data for media source
            MediaSource ms = CMSDialogHelper.GetMediaData(url, siteName);
            if (ms != null)
            {
                SessionHelper.SetValue("MediaSource", ms);

                // Preselect the tab
                if (!selectionTable.Contains(DialogParameters.EMAIL_TO) || !selectionTable.Contains(DialogParameters.ANCHOR_NAME))
                {
                    switch (ms.SourceType)
                    {
                    case MediaSourceEnum.DocumentAttachments:
                    case MediaSourceEnum.MetaFile:
                        query = URLHelper.AddUrlParameter(query, "tab", "attachments");
                        break;

                    case MediaSourceEnum.Content:
                        query = URLHelper.AddUrlParameter(query, "tab", "content");
                        break;

                    case MediaSourceEnum.MediaLibraries:
                        query = URLHelper.AddUrlParameter(query, "tab", "libraries");
                        break;

                    default:
                        query = URLHelper.AddUrlParameter(query, "tab", "web");
                        break;
                    }
                }

                // Update old format url
                if ((selectionTable.Contains(DialogParameters.URL_OLDFORMAT)) && (selectionTable.Contains(DialogParameters.URL_GUID)))
                {
                    if (String.IsNullOrEmpty(siteName))
                    {
                        siteName = SiteContext.CurrentSiteName;
                    }
                    string outUrl = ModuleCommands.MediaLibraryGetMediaFileUrl(selectionTable[DialogParameters.URL_GUID].ToString(), siteName);
                    if (!String.IsNullOrEmpty(outUrl))
                    {
                        selectionTable[DialogParameters.URL_URL] = outUrl;
                    }
                }

                // Set extension if not exist in selection table
                if ((selectionTable[DialogParameters.URL_EXT] == null) || ((selectionTable[DialogParameters.URL_EXT] != null) && (String.IsNullOrEmpty(selectionTable[DialogParameters.URL_EXT].ToString()))))
                {
                    selectionTable[DialogParameters.URL_EXT] = ms.Extension;
                }

                // Update selection table if only URL presents
                if (selectionTable.Contains(DialogParameters.URL_URL))
                {
                    switch (ms.MediaType)
                    {
                    case MediaTypeEnum.Image:
                        // Image
                        selectionTable[DialogParameters.IMG_URL]    = UrlResolver.ResolveUrl(selectionTable[DialogParameters.URL_URL].ToString());
                        selectionTable[DialogParameters.IMG_WIDTH]  = selectionTable[DialogParameters.URL_WIDTH];
                        selectionTable[DialogParameters.IMG_HEIGHT] = selectionTable[DialogParameters.URL_HEIGHT];
                        break;

                    case MediaTypeEnum.AudioVideo:
                        // Media
                        selectionTable[DialogParameters.AV_URL]    = UrlResolver.ResolveUrl(selectionTable[DialogParameters.URL_URL].ToString());
                        selectionTable[DialogParameters.AV_WIDTH]  = selectionTable[DialogParameters.URL_WIDTH];
                        selectionTable[DialogParameters.AV_HEIGHT] = selectionTable[DialogParameters.URL_HEIGHT];
                        selectionTable[DialogParameters.AV_EXT]    = ms.Extension;
                        break;
                    }

                    if ((ms.SourceType == MediaSourceEnum.Content) && (ms.FileName != null) && (OutputFormat == OutputFormatEnum.NodeGUID))
                    {
                        string fileUrl = AttachmentURLProvider.GetPermanentAttachmentUrl(ms.NodeGuid, ValidationHelper.GetSafeFileName(ms.FileName, siteName));
                        selectionTable[DialogParameters.URL_URL] = UrlResolver.ResolveUrl(fileUrl);
                    }
                    else if (OutputFormat != OutputFormatEnum.URL)
                    {
                        selectionTable[DialogParameters.URL_URL] = UrlResolver.ResolveUrl(selectionTable[DialogParameters.URL_URL].ToString());
                    }

                    selectionTable[DialogParameters.FILE_NAME] = ms.FileName;
                    selectionTable[DialogParameters.FILE_SIZE] = ms.FileSize;
                }

                // Add original size into table
                selectionTable[DialogParameters.IMG_ORIGINALWIDTH]  = ms.MediaWidth;
                selectionTable[DialogParameters.IMG_ORIGINALHEIGHT] = ms.MediaHeight;
            }
            else
            {
                if (selectionTable.Contains(DialogParameters.EMAIL_TO))
                {
                    query = URLHelper.AddUrlParameter(query, "tab", "email");
                }
                if (selectionTable.Contains(DialogParameters.ANCHOR_NAME))
                {
                    query = URLHelper.AddUrlParameter(query, "tab", "anchor");
                }
            }

            query = URLHelper.AddUrlParameter(query, "hash", QueryHelper.GetHash(query));
            insertHeaderLocation = BaseFilePath + "Header.aspx" + query;
        }


        // Set selected item into session
        SessionHelper.SetValue("DialogParameters", selectionTable);

        if ((anchorsList != null) && (anchorsList.Count > 0))
        {
            SessionHelper.SetValue("Anchors", anchorsList);
        }
        if ((idsList != null) && (idsList.Count > 0))
        {
            SessionHelper.SetValue("Ids", idsList);
        }

        if (((selectionTable[DialogParameters.LINK_TEXT] != null) &&
             (selectionTable[DialogParameters.LINK_TEXT].ToString() == "##LINKTEXT##")) ||
            ((selectionTable[DialogParameters.EMAIL_LINKTEXT] != null) &&
             (selectionTable[DialogParameters.EMAIL_LINKTEXT].ToString() == "##LINKTEXT##")) ||
            ((selectionTable[DialogParameters.ANCHOR_LINKTEXT] != null) &&
             (selectionTable[DialogParameters.ANCHOR_LINKTEXT].ToString() == "##LINKTEXT##")))
        {
            SessionHelper.SetValue("HideLinkText", true);
        }

        ltlScript.Text = ScriptHelper.GetScript("if (window.parent.frames['insertHeader']) { window.parent.frames['insertHeader'].location= \"" + ResolveUrl(insertHeaderLocation) + "\";} ");
    }
Ejemplo n.º 42
0
        /// <summary>
        /// Create a playback list from the list of songs received from the foreground app.
        /// </summary>
        /// <param name="songs"></param>
        private async Task CreatePlaybackList(QuranAudioTrack newTrack)
        {
            BackgroundMediaPlayer.Current.Pause();

            // Make a new list
            if (_playbackList != null)
            {
                _playbackList.CurrentItemChanged -= PlaybackListCurrentItemChanged;
                _playbackList.Items.Clear();
            }
            else
            {
                _playbackList = new MediaPlaybackList();
            }

            // Initialize FileUtils
            await FileUtils.Initialize(newTrack.ScreenInfo);

            var missingFiles = await AudioUtils.GetMissingFiles(newTrack);

            // Add playback items to the list
            QuranAudioTrack nextTrack = newTrack.GetFirstAyah();
            var             reciter   = nextTrack.GetReciter();

            while (nextTrack != null)
            {
                string      fileName = AudioUtils.GetFileName(nextTrack.GetQuranAyah(), reciter);
                MediaSource source;
                if (missingFiles.Contains(fileName))
                {
                    source = MediaSource.CreateFromUri(new Uri(Path.Combine(reciter.ServerUrl, fileName)));
                }
                else
                {
                    var file = await FileUtils.GetFile(await reciter.GetStorageFolder(), fileName);

                    if (file != null)
                    {
                        source = MediaSource.CreateFromStorageFile(file);
                        //source = MediaSource.CreateFromUri(new Uri(file.Path));
                    }
                    else
                    {
                        source = MediaSource.CreateFromUri(new Uri(Path.Combine(reciter.ServerUrl, fileName)));
                    }
                }
                source.CustomProperties[SurahKey]      = nextTrack.Surah;
                source.CustomProperties[AyahKey]       = nextTrack.Ayah;
                source.CustomProperties[ReciterKey]    = nextTrack.ReciterId;
                source.CustomProperties[QuranTrackKey] = nextTrack.ToString();
                source.CustomProperties[TitleKey]      = QuranUtils.GetSurahAyahString(nextTrack.Surah, nextTrack.Ayah);
                _playbackList.Items.Add(new MediaPlaybackItem(source));
                nextTrack = nextTrack.GetNextInSurah();
            }

            // Don't auto start
            BackgroundMediaPlayer.Current.AutoPlay = false;

            // Assign the list to the player
            BackgroundMediaPlayer.Current.Source = _playbackList;

            // Add handler for future playlist item changes
            _playbackList.CurrentItemChanged += PlaybackListCurrentItemChanged;
        }
Ejemplo n.º 43
0
        void BuildTopology(MediaSource source, Topology topology)
        {
            using (var presentationDescriptor = source.CreatePresentationDescriptor())
                foreach (var stream in presentationDescriptor.Streams.Where(s => s.IsSelected))
                    using (var sourceNode = TopologyNode.Create(MFTopologyType.SourcestreamNode))
                    {
                        if (!stream.MediaType.IsAudio && !stream.MediaType.IsVideo)
                            throw new Exception("Unknown stream format!");

                        sourceNode.TopNodeSource = source;
                        sourceNode.TopNodePresentationDescriptor = presentationDescriptor;
                        sourceNode.TopNodeStreamDescriptor = stream;

                        using (var outputNode = TopologyNode.Create(MFTopologyType.OutputNode))
                        {
                            outputNode.Object = stream.MediaType.IsAudio ? Activate.CreateAudioRenderer() : Activate.CreateVideoRenderer(hwndVideo);

                            topology.Add(sourceNode);
                            topology.Add(outputNode);
                            sourceNode.ConnectOutput(0, outputNode, 0);
                        }
                    }
        }
    protected void imgRefresh_Click(object sender, EventArgs e)
    {
        if (plcMediaType.Visible)
        {
            MediaSource source = CMSDialogHelper.GetMediaData(txtUrl.Text, null);
            if ((source == null) || (source.MediaType == MediaTypeEnum.Unknown))
            {
                Properties.ItemNotSystem = true;

                // Try get source type from URL extension
                int index = txtUrl.Text.LastIndexOfCSafe('.');
                if (index > 0)
                {
                    string ext = txtUrl.Text.Substring(index);
                    if (ext.Contains("?"))
                    {
                        ext = URLHelper.RemoveQuery(ext);
                    }
                    if (source == null)
                    {
                        source = new MediaSource();
                    }
                    source.Extension = ext;
                    if (source.MediaType == MediaTypeEnum.Image)
                    {
                        // Get the data
                        GetExternalImageDimensions(txtUrl.Text.Trim());
                    }
                    else
                    {
                        source.MediaWidth = 300;
                        source.MediaHeight = 200;
                    }
                }
            }
            else
            {
                Properties.ItemNotSystem = false;
            }

            if (source != null)
            {
                // Set default dimensions when not specified
                if ((mWidth == 0) && (mHeight == 0))
                {
                    mWidth = source.MediaWidth;
                    mHeight = source.MediaHeight;
                }
                switch (source.MediaType)
                {
                    case MediaTypeEnum.Image:
                        drpMediaType.SelectedValue = "image";
                        break;

                    case MediaTypeEnum.AudioVideo:
                        drpMediaType.SelectedValue = "av";
                        break;

                    case MediaTypeEnum.Flash:
                        drpMediaType.SelectedValue = "flash";
                        break;
                    default:
                        drpMediaType.SelectedValue = "";
                        plcInfo.Visible = true;
                        lblInfo.ResourceString = "dialogs.web.selecttype";
                        break;
                }
            }

            if (source != null)
            {
                SetLastType(source.MediaType);
            }

            ShowProperties();
        }
    }
 public MediaModel(StorageFile file)
 {
     MediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(file));
 }
Ejemplo n.º 46
0
 public VideoPlayer(MediaSource source)
 {
     _source = source;
 }
Ejemplo n.º 47
0
 public VideoPlayer(MediaSource source)
 {
     _source = source;
 }
Ejemplo n.º 48
0
        public void Update()
        {
            if (!gameOver)
            {
                if (isUserPaddleMovingLeftward)
                {
                    if (userPaddle.X > leftWall.X + leftWall.Width)
                    {
                        moveUserPaddle(-5);
                    }
                }
                if (isUserPaddleMovingRightward)
                {
                    if (userPaddle.X + userPaddle.Width < rightWall.X)
                    {
                        moveUserPaddle(5);
                    }
                }

                if (ball.X - ball.Radius <= leftWall.X + leftWall.Width &&
                    ball.Y + ball.Radius >= leftWall.Y && ball.Y + ball.Radius <= leftWall.Y + leftWall.Height)
                {
                    ball.movingLeftward = false;
                    //ball.ChangeColor();
                }
                else if (ball.X + ball.Radius >= rightWall.X &&
                         ball.Y + ball.Radius >= rightWall.Y && ball.Y + ball.Radius <= rightWall.Y + leftWall.Height)
                {
                    ball.movingLeftward = true;
                    // ball.ChangeColor();
                }

                if (ball.Y - ball.Radius <= computerPaddle.Y + computerPaddle.Height &&
                    ball.X - ball.Radius >= computerPaddle.X &&
                    ball.X + ball.Radius <= computerPaddle.X + computerPaddle.Width)
                {
                    ball.movingDownward = true;
                    //ball.ChangeColor();
                }
                else if (ball.Y + ball.Radius >= userPaddle.Y &&
                         ball.X - ball.Radius >= userPaddle.X &&
                         ball.X + ball.Radius <= userPaddle.X + userPaddle.Width)
                {
                    ball.movingDownward = false;
                    //ball.ChangeColor();
                }

                computerPaddle.X = ball.X - computerPaddle.Width / 2;


                ball.updatePosition();

                if (ball.Y < computerPaddle.Y || ball.Y > userPaddle.Y)
                {
                    gameOver = true;
                    App.soundPlayer.Source = MediaSource.CreateFromUri(
                        new Uri($"ms-appx:///Assets/Wa-wa-wa-sound.mp3"));
                    App.soundPlayer.Play();
                }
            }
        }
 public TranscodePlayer(MediaSource source)
 {
     _source = source;
 }
Ejemplo n.º 50
0
        public async void Handle(UpdateCall update)
        {
            _call = update.Call;

            if (update.Call.State is CallStatePending pending)
            {
                if (update.Call.IsOutgoing && pending.IsCreated && pending.IsReceived)
                {
                    if (pending.IsCreated && pending.IsReceived)
                    {
                        _mediaPlayer.Source           = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/Audio/voip_ringback.mp3"));
                        _mediaPlayer.IsLoopingEnabled = true;
                        _mediaPlayer.Play();
                    }
                }
            }
            if (update.Call.State is CallStateReady ready)
            {
                var user = CacheService.GetUser(update.Call.UserId);
                if (user == null)
                {
                    return;
                }

                VoIPControllerWrapper.UpdateServerConfig(ready.Config);

                var logFile       = Path.Combine(ApplicationData.Current.LocalFolder.Path, $"{SessionId}", $"voip{update.Call.Id}.txt");
                var statsDumpFile = Path.Combine(ApplicationData.Current.LocalFolder.Path, $"{SessionId}", "tgvoip.statsDump.txt");

                var call_packet_timeout_ms  = CacheService.Options.CallPacketTimeoutMs;
                var call_connect_timeout_ms = CacheService.Options.CallConnectTimeoutMs;

                if (_controller != null)
                {
                    _controller.Dispose();
                    _controller = null;
                }

                var config = new VoIPConfig
                {
                    initTimeout = call_packet_timeout_ms / 1000.0,
                    recvTimeout = call_connect_timeout_ms / 1000.0,
                    dataSaving  = base.Settings.UseLessData,
                    enableAEC   = true,
                    enableNS    = true,
                    enableAGC   = true,

                    enableVolumeControl = true,

                    logFilePath       = logFile,
                    statsDumpFilePath = statsDumpFile
                };

                _controller = new VoIPControllerWrapper();
                _controller.SetConfig(config);
                _controller.CurrentAudioInput  = SettingsService.Current.VoIP.InputDevice;
                _controller.CurrentAudioOutput = SettingsService.Current.VoIP.OutputDevice;
                _controller.SetInputVolume(SettingsService.Current.VoIP.InputVolume);
                _controller.SetOutputVolume(SettingsService.Current.VoIP.OutputVolume);

                _controller.CallStateChanged += (s, args) =>
                {
                    BeginOnUIThread(() =>
                    {
                        if (args == libtgvoip.CallState.WaitInit || args == libtgvoip.CallState.WaitInitAck)
                        {
                            _mediaPlayer.Source           = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/Audio/voip_connecting.mp3"));
                            _mediaPlayer.IsLoopingEnabled = false;
                            _mediaPlayer.Play();
                        }
                        else if (args == libtgvoip.CallState.Established)
                        {
                            _callStarted        = DateTime.Now;
                            _mediaPlayer.Source = null;
                        }
                    });
                };

                BeginOnUIThread(() =>
                {
                    Show(update.Call, _controller, _callStarted);
                });

                var endpoints = new Endpoint[ready.Connections.Count];

                for (int i = 0; i < endpoints.Length; i++)
                {
                    endpoints[i] = ready.Connections[i].ToEndpoint();
                }

                _controller.SetEncryptionKey(ready.EncryptionKey.ToArray(), update.Call.IsOutgoing);
                _controller.SetPublicEndpoints(endpoints, ready.Protocol.UdpP2p && ready.AllowP2p, ready.Protocol.MaxLayer);
                _controller.Start();
                _controller.Connect();
            }
            else if (update.Call.State is CallStateDiscarded discarded)
            {
                if (discarded.NeedDebugInformation)
                {
                    ProtoService.Send(new SendCallDebugInformation(update.Call.Id, _controller.GetDebugLog()));
                }

                if (discarded.NeedRating)
                {
                    BeginOnUIThread(async() => await SendRatingAsync(update.Call.Id));
                }

                _controller?.Dispose();
                _controller = null;
                _call       = null;
            }

            await Dispatcher.DispatchAsync(() =>
            {
                switch (update.Call.State)
                {
                case CallStateDiscarded discarded:
                    if (update.Call.IsOutgoing && discarded.Reason is CallDiscardReasonDeclined)
                    {
                        _mediaPlayer.Source           = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/Audio/voip_busy.mp3"));
                        _mediaPlayer.IsLoopingEnabled = true;
                        _mediaPlayer.Play();

                        Show(update.Call, null, _callStarted);
                    }
                    else
                    {
                        _mediaPlayer.Source = null;

                        Hide();
                    }
                    break;

                case CallStateError error:
                    Hide();
                    break;

                default:
                    Show(update.Call, null, _callStarted);
                    break;
                }
            });
        }
        private void ProcessPlayerClosed()
        {
            // The session finished to close, we have to dispose all related object.
            currentMusic = null;

            mediaSessionCallback.Dispose();

            if (mediaSource != null) mediaSource.Shutdown();
            if (mediaSession != null) mediaSession.Shutdown();

            if (streamVolume != null) streamVolume.Dispose();
            if (mediaSource != null) mediaSource.Dispose();
            if (topology != null) topology.Dispose();
            if (mediaSession != null) mediaSession.Dispose();
            if (mediaInputByteStream != null) mediaInputByteStream.Dispose();

            topology = null;
            streamVolume = null;
            mediaSession = null;
            mediaSource = null;
            mediaInputByteStream = null;
            mediaSessionCallback = null;
            isMusicPlayerReady = false;
        }
Ejemplo n.º 52
0
        static void Main()
        {
            Console.WriteLine("WebRTC Server Sample Program");
            Console.WriteLine("Press ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource exitCts = new CancellationTokenSource(); // Cancellation token to stop the SIP transport and RTP stream.
            ManualResetEvent        exitMre = new ManualResetEvent(false);

            AddConsoleLogger();

            if (!File.Exists(MP4_FILE_PATH))
            {
                throw new ApplicationException($"The media file at does not exist at {MP4_FILE_PATH}.");
            }
            else if (!File.Exists(DTLS_CERTIFICATE_PATH))
            {
                throw new ApplicationException($"The DTLS certificate file could not be found at {DTLS_CERTIFICATE_PATH}.");
            }
            else if (!File.Exists(DTLS_KEY_PATH))
            {
                throw new ApplicationException($"The DTLS key file could not be found at {DTLS_KEY_PATH}.");
            }

            // Initialise OpenSSL & libsrtp, saves a couple of seconds for the first client connection.
            Console.WriteLine("Initialising OpenSSL and libsrtp...");
            DtlsHandshake.InitialiseOpenSSL();
            Srtp.InitialiseLibSrtp();

            Task.Run(DoDtlsHandshakeLoopbackTest).Wait();

            Console.WriteLine("Test DTLS handshake complete.");

            _mediaSource = new MediaSource();
            _mediaSource.Init(MP4_FILE_PATH, true);
            //_mediaSource.Init(0, 0, VideoSubTypesEnum.I420, 640, 480);

            // Start web socket.
            Console.WriteLine("Starting web socket server...");
            _webSocketServer = new WebSocketServer(IPAddress.Any, WEBSOCKET_PORT, true);
            _webSocketServer.SslConfiguration.ServerCertificate          = new System.Security.Cryptography.X509Certificates.X509Certificate2(WEBSOCKET_CERTIFICATE_PATH);
            _webSocketServer.SslConfiguration.CheckCertificateRevocation = false;
            //_webSocketServer.Log.Level = WebSocketSharp.LogLevel.Debug;
            _webSocketServer.AddWebSocketService <SDPExchange>("/", (sdpExchanger) =>
            {
                sdpExchanger.WebSocketOpened   += SendSDPOffer;
                sdpExchanger.OnMessageReceived += WebSocketMessageReceived;
            });
            _webSocketServer.Start();

            Console.WriteLine($"Waiting for browser web socket connection to {_webSocketServer.Address}:{_webSocketServer.Port}...");

            // Ctrl-c will gracefully exit the call at any point.
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                exitMre.Set();
            };

            // Wait for a signal saying the call failed, was cancelled with ctrl-c or completed.
            exitMre.WaitOne();

            _mediaSource.Shutdown();
            _webSocketServer.Stop();
        }
Ejemplo n.º 53
0
        public void Transcode(MediaSource source, string mcxuser)
        {
            // Modified to ensure a user will only transcode one file at a time.
            string key = source.Key;
            lock (sTranscoders)
            {
                if (sTranscoders.ContainsKey(key))
                {
                    // Transcoding service is/was allready transcoding the file
                    Utilities.DebugLine("Transcode [Already Processing]: {0}, status={1}", source, sTranscoders[key].Status);

                    if ((sTranscoders[key].Status == TranscodingStatus.BufferReady) ||
                        (sTranscoders[key].Status == TranscodingStatus.Done) ||
                        (sTranscoders[key].Status == TranscodingStatus.Initializing))
                    {
                        NotifyAll(key, sTranscoders[key].Status);
                        return;
                    }
                }
            }

            // This file if not allready being transcoded. Check user is not allready transcoding
            lock (sUserSession)
            {
                if (sUserSession.ContainsKey(mcxuser))
                {
                    // Allready transcoding, cancel the job
                    Utilities.DebugLine("Transcode [User allready transcoding]: {0}", mcxuser);
                    if (sTranscoders.ContainsKey(sUserSession[mcxuser]))
                    {
                        if ((sTranscoders[sUserSession[mcxuser]].Status == TranscodingStatus.BufferReady) ||
                            (sTranscoders[sUserSession[mcxuser]].Status == TranscodingStatus.Initializing))
                        {
                            Cancel(sUserSession[mcxuser]);
                        }
                    }
                    sUserSession.Remove(mcxuser);
                }
            }

            // Start transcoding session
            sTranscoders[key] = new Transcoder(source);
            sUserSession[mcxuser] = key;
        }
Ejemplo n.º 54
0
 public static void PlayButton2()
 {
     MusicPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Audio/button2.wav", UriKind.Absolute));
     MusicPlayer.MediaPlayer.Play();
 }
Ejemplo n.º 55
0
 public HDDVDPlayer(MediaSource source, string mediaPath)
 {
     _source = source;
     _mediaPath = mediaPath;
 }
Ejemplo n.º 56
0
 public static void PlayBgm()
 {
     BgmPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Audio/bgm1.mp3", UriKind.Absolute));
     BgmPlayer.MediaPlayer.Play();
 }
 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);
     }
 }
Ejemplo n.º 58
0
 public MediaPlayerViewModel()
 {
     Source       = MediaSource.CreateFromUri(new Uri(DefaultSource));
     PosterSource = DefaultPoster;
 }
 private void MediaSourceOnStateChanged(MediaSource sender, MediaSourceStateChangedEventArgs args)
 {
     switch (args.NewState)
     {
         case MediaSourceState.Initial:
             Status = MediaPlayerStatus.Loading;
             break;
         case MediaSourceState.Opening:
             Status = MediaPlayerStatus.Loading;
             break;
         case MediaSourceState.Failed:
             Status = MediaPlayerStatus.Failed;
             break;
         case MediaSourceState.Closed:
             Status = MediaPlayerStatus.Stopped;
             break;
         case MediaSourceState.Opened:
             break;
         default:
             throw new ArgumentOutOfRangeException();
     }
 }
Ejemplo n.º 60
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);
        }