How to Play .mp3/.Wma Music in a Metro App

Here is how to do it:

1. Open VS 2012 for Windows 8

2. Create a new blank project of type Blank App/C#

3. Paste this code into the <Grid> element in MainPage.xaml

XML
<Grid.ColumnDefinitions>
    <ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<MediaElement x:Name="mediaElement" Grid.Column="0" Grid.Row="0" IsMuted="False" Volume="100" AudioCategory="ForegroundOnlyMedia" PosterSource="Assets/Logo.png" RealTimePlayback="False" AutoPlay="True" Height="100" Width="100"></MediaElement>

4. Paste this code into the class MainPage in MainPage.xaml.cs

C#
IRandomAccessStreamWithContentType stream = null;
void OpenSong()
{
    Windows.Storage.KnownFolders.MusicLibrary.GetFileAsync(&quot;_.mp3&quot;).Completed = (async, status) =&gt;
    {
        if (async.Status == AsyncStatus.Completed)
        {
            StorageFile storageFile = async.GetResults();
            storageFile.OpenReadAsync().Completed = (async2, status2) =&gt;
            {
                if (async2.Status == AsyncStatus.Completed)
                {
                    stream = (IRandomAccessStreamWithContentType)async2.GetResults();
                    this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, PlaySong).Completed = (async3, status3) =&gt;
                    {
                    };
                }
            };
        }
    };
}
void PlaySong()
{
    //-Setting only the Source property is not enough, it would not play for me that way; it has to be done through the SetSource method
    mediaElement.SetSource(stream, stream.ContentType);
    mediaElement.Play();
}

5. Call the OpenSong() method in the empty OnNavigatedTo() method. If you call it in the constructor, you will not get any error, but the sound simply will not play

C#
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    OpenSong();
}

6. Create a music file _.mp3 in the W8 Music library

7. Enable, in the Package.appxmanifest file, access to the Music library

8. Run the program and test it

Categories

Leave a Reply