Question

i`m using mediaElement to play background music in my app. And that works just fine.

Problem is when the user minimize the application. When the application resume there is no sound... I can play other sounds in my application but cant play that background music any more.

First i have this code to stop all background music at first time app open:

if (Microsoft.Xna.Framework.Media.MediaPlayer.State == MediaState.Playing)
        {

            Microsoft.Xna.Framework.Media.MediaPlayer.Pause();
            FrameworkDispatcher.Update();

        }

xaml code of that mediaElement

 <MediaElement AutoPlay="True" Source="/Dodaci/pozadina.mp3" x:Name="muzika_pozadina" MediaEnded="pustiPonovo" Loaded="pustiPonovo"   />

and the cs code

private void pustiPonovo(object sender, RoutedEventArgs e)
    {
        muzika_pozadina.Play();
    }

sound is about 300kb size.

So, how can i resume that sound playing after the user resume the application?

Was it helpful?

Solution

When your App is put into Dormant State (when you hit Start buton for example), the MediaElement is stopped. Then after you return to your App (and it wasn't Tombstoned), the Page is not Initialized once again, which means that your MediaElement is not loaded once again, so your Music doesn't start once again.

It depends on your purpose and code how it can be returned. In very simple example when you don't need to remember music last position you can just set source of your MediaElement once again in OnNavigatedTo() event:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    if (e.NavigationMode == NavigationMode.Back)
            muzika_pozadina.Source = new Uri("/Dodaci/pozadina.mp3", UriKind.RelativeOrAbsolute);
}

As you have set your MediaElement.AutoPlay to true - it should start automatically (because of that you probably also don't need your Loaded event pustiPonovo).

In more complicated cases you can take an advantage of Activation and Deactivation events of your App - returning to MediaElement from Dormant/Tombstoned case is well explained here in the article.

You should also read about Fast App Resume in case User decides to return to your App by Tile instead of Launchers-Choosers.

I haven't tried above code, but hopefully it will do the job.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top