ARTICLE

Playing Background Music in Windows Store Applications

Posted by Ibrahim Ersoy Articles | Windows Store Apps November 24, 2012
You have an awesome sound and you'd like to play it in your app or game looping whether you navigate to another page or not.. So, read this article and learn how.
Reader Level:

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!

Login to add your contents and source code to this article
post comment
     

Your welcome! Yes there s a rule that you need to let user to mute the music.As i described at the last part of the article you can set a sound's ismute property as true or false according to user's option.For that the best thing is doing it classic way by using a button or using new ToggleSwitch control which takes 2 values: On or Off .i believe muting it on or off would be enough.No need to set volume level.

Posted by Ibrahim Ersoy Dec 02, 2012

Thanks for this great article. I wonder are there any specific certification requirements that need to be take care of when having backgroun audio on all pages like: - Provide On/Off button for music - Provide volume settings feature Thanks.

Posted by Mild Dec 02, 2012

Thanks.. for Explanation..

Posted by Gaurav Gupta Nov 26, 2012

No Gaurav,just embed it in StandardStyles.xaml page.it implements the style properties of the page thats why your MediaElement defined in that page will become global and can be accessed anywhere using the same codes in MainPage.xaml.cs. But if you have multiple Style Pages,you may need to re-define the MediaElement for each Style Page.

Posted by Ibrahim Ersoy Nov 26, 2012

Can I need to embed Media Element code in every page?

Posted by Gaurav Gupta Nov 25, 2012
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter