Playing Background Music in Windows Store Applications

This article is a proven experience from a global contest I recently joined.

I've built an application with 2-3 pages that has a sound playing in the background. Even when it navigates among pages, the music plays like a background task.

So let's start building the application.

Counting on you have a sound file (mp3 is preferred) and have added 2 pages.

The trick to do it is to make some modifications in 3 files in your Windows Store App:

  1. Common/StandardStyles.xaml
  2. App.xaml.cs
  3. MainPage.xaml.cs (MainScreen of your app)

Modifying StandardStyles

To add a global background music you need to add it as a style and embed the MediaElement file inside this style. This will make it global.

Add this style to a Common/StandardStyles.xaml Page:

<Style x:Key="RootFrameStyle" TargetType="Frame">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Frame">
                <Grid>
                    <MediaElement x:Name="MediaPlayer" IsLooping="True" Source="ms-appx:///Sounds/Sound1.mp3"
                                     AudioCategory
="BackgroundCapableMedia" AutoPlay="True" />
                    <!-- if you need other musics to play,embed them here !-->
                    <ContentPresenter />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</
Style>

Modifying App.xaml.cs

For modification you should check out the OnLaunched event and update its "if (rootFrame == null)" block as follows:

protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    Frame rootFrame = Window.Current.Content as Frame;  
    if (rootFrame == null)
    {
        rootFrame = new Frame();   
        if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
        { 
        } 
        rootFrame.Style = Resources["RootFrameStyle"] as Style;
        Window.Current.Content = rootFrame;
    } 
    if (rootFrame.Content == null)
    {
        if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
        {
            throw new Exception("Failed to create initial page");
        }
    } 
    Window.Current.Activate();
}

Modifying MainPage.xaml.cs

To play the background sound in MainPage you need to get the items from ControlTemplate. For this the best way is to look up VisualTreeHelper and its children.

First define a MediaElement as public so that you can access it to stop, play, pause or do other things.

    MediaElement rootMediaElement;

Later in MainPage's loaded event, note this code to look up the requested sound:

    DependencyObject rootGrid = VisualTreeHelper.GetChild(Window.Current.Content, 0);
    rootMediaElement = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 0);


Now run your application and test it! You'll listen to the music even it plays in all pages continously.

Let me explain the last code:

The first line of code helps us to bring the first grid of the style.
The second line of code helps us to look for a MediaElement element and if found assigning the values of it to our newly created MediaElement "rootMediaElement"; see:

    rootMediaElement = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 0);

The "0" value in this code defines the first MediaElement we added in Common/StandardStyles.xaml file.

If you had another MediaElement and wanted it to play like here:

<Style x:Key="RootFrameStyle" TargetType="Frame">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Frame">
                <Grid>
                    <MediaElement x:Name="MediaPlayer" IsLooping="True" Source="ms-appx:///Sounds/Sound1.mp3"
                                AudioCategory
="BackgroundCapableMedia" AutoPlay="True" />
                    <MediaElement x:Name="buttonses" IsLooping="False" Source="ms-appx:///Sounds/Sound2.mp3"
                                AudioCategory
="BackgroundCapableMedia" AutoPlay="False" />
                    <ContentPresenter />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</
Style>

If you wanted to play "Sound2.mp3" as described above you need to define:

    DependencyObject rootGrid = VisualTreeHelper.GetChild(Window.Current.Content, 0);
    rootMediaElement = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 1);


"1" refers to the second item of the grid in your style.

If you want to mute it on or off then you can use this code in a button click event:

    rootMediaElement.IsMuted = true;

And if there's a problem playing the sound, you can check your Manifest file and add a BackgroundTask with an Audio Type as added here:

metro6.png

The Package file can be found in your Solution, just double-click on it!

I'm pretty sure this method I described will help you at some point of time when you're building a game or application.

If you still have problems, please let me know so that I can help you!

Hope you liked it!

Up Next
    Ebook Download
    View all
    Learn
    View all
    Araf Global is a software consultancy company founded in 2016 focusing on cutting edge technologies.