Share via


Using a Downloader object with MediaElement in WPF/E

A 70 meg video isn't the nicest thing to download and have no feedback from the UI when you are looking at my WPF/E video player so I changed the code to use a Downloader object.

 //Create downloader object
    var control = sender.getHost();
    var downloader = control.createObject("downloader");
    downloader.downloadProgressChanged = "javascript:onDownloadProgressChanged";
    downloader.completed = "javascript:onDownloadCompleted";
    downloader.open("GET", "T2_720.wmv", true);
    downloader.send();

The Downloader object helps by avoiding the need to download all the content as soon as we load the HTML page or XAML content. It acts like the XmlHttpRequest (the backbone of Ajax) and means that the pages do not need to be refreshed. Perfect for downloading byte-heavy media content.

So it will go off and download the T2_720.wmv file in the background. Meanwhile, we want to show progress of that download so hook up our downloader object to onDownloadProgressChanged and in that method we modify a TextBlock to show a percentage downloaded:

 function onDownloadProgressChanged(sender, eventArgs)
{
    var percentage = Math.floor(sender.downloadProgress * 100);
    sender.findName("PlayText").text = percentage + "%";
}

And once the object has been downloaded we handle that in the Completed event. The last thing that is important is to set our MediaElement source to the object that has been downloaded using the setSource() method. Rather than using the Source property.

 function onDownloadCompleted(sender, eventArgs)
{
    sender.findName("PlayText").text = "Play";
    var host = document.getElementById("wpfeControl1");
    host.findName("VideoElement").setSource(sender);
    host.findName("VideoElement").Opacity=100;
    host.findName("background").Opacity= 0; 
}

 

There is a great article in the WPFE SDK (available online and offline) - MSDN Article: Using the WPF/E Downloader Object