Programming Pitfalls: WinRT MediaElement URL Scheme

Jan 26, 2013 | C#, Microsoft, Programming

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.

More from Mike:

About Me

Hi! I’m Mike! I’m a software engineer who codes at The Mad Botter INC. You might know me from Coder Radio or The Mike Dominick Show.  Drop me a line if you’re interested in having some custom mobile or web development done.

Follow Me

© 2024 Copyright Michael Dominick | All rights reserved