I’ve been doing a good deal of C# WinRT development recently and for the most part it hasn’t been bad. This week, however, I found a pitfall that is not only so simple it’s silly but also managed to waste an hour or so of my time. WinRT has a class called MediaElement that allows you to play different types of media using Window’s built in media engine.
As you might expect, instances of MediaElement take Uri’s for their source media. So, let’s say you want to play a video from your app’s bundle — perhaps an introductory video or something like that. You might try:
// I am assuming you created a MediaElement called "player" in your XAML player.Source = new Uri("/Appname/Assets/Media/Video.wmv" UriKind.Absolute); player.Play();
Sadly, that will crash every-time. The good news is that your logic is fine, but the bad news is that you are missing a silly implementation detail of how Microsoft has decided to refer to in bundle URL’s. To make that code work, you simply need to make one small change:
// I am assuming you created a MediaElement called "player" in your XAML player.Source = new Uri("ms-appx:/Appname/Assets/Media/Video.wmv" UriKind.Absolute); player.Play();
That’s it. Clearly, there is a little bit of magic here… hence the need for the prefix, but it works and is the prescribed way to do this according to MSDN. Hope that helps someone. Questions? Comments? Find me on Twitter and Google+. This post was brought to you by Code Journal and Fingertip Tech, INC.