When building WinRT applications it is going to be pretty common to want to play some sort of embedded audio file. It may also be common to want to play this file but via a ViewModel (or simply not in a view). In this post we are going to take a quick look at how to play an MP3 file by using the MediaElement control, but we will NOT be doing this via XAML, we will be doing via straight up code. The reason I am not using XAML here is because i don’t want to limit the places or times I can play audio, also I want to trigger the playing of the file via my ViewModel.
Before we get coding lets assume we have an audio file embedded in our application under the /Assests/SoundFiles folder and the file name is ding.mp3
private MediaElement _mediaElement;
public async Task Play( string fileName)
var packageLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
var assetsFolder = await packageLocation.GetFolderAsync("assets");
var soundsFolder = await assetsFolder.GetFolderAsync("soundFiles");
var myAudio = await soundsFolder.GetFileAsync(fileName); // would be ding.mp3
_mediaElement = new MediaElement();
var stream = await myAudio.OpenAsync(FileAccessMode.Read);
In the code above you can see that we are doing the following things.
- Getting the StorageFile reference to Ding.mp3
- Creating a new instance of the MediaElement (this is class level because I found the audio would not play if it were a local instance)
- Open the StorageFile and get the Stream reference of the file
- Set the Stream reference as the source for the MediaElement
- Call Play
Now in theory you should be able to set the ‘source’ property to the file path, but i was not able to get this to work. This may have been my error or could be an issue with the MediaElement.
As you can see this is not too complicated and requires almost no code
Till next time,
07-14-2012 12:39 PM