Question

Here is my xaml code:

<MediaElement x:Name="beepSound" Source="/Sounds/beep.mp3" AutoPlay="False" Visibility="Collapsed"/>

C# code:

private void ButtonClick(object sender, RoutedEventArgs e)
{
    if (beepSound.CurrentState == System.Windows.Media.MediaElementState.Playing)
        beepSound.Pause();
    else
        beepSound.Play();
}

This code works perfectly. But after I resume the app (by pressing start button and then back again into the app) the sound doesn't play. What causes this behavior? Is there anything wrong with my code?

Was it helpful?

Solution 2

After a bit of research I found out that, after the app resumes it loses its source information. So you have to set the source again. Here is how I did it.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    beepSound.Source = new Uri("/Sounds/beep.mp3", UriKind.Relative);
}

OTHER TIPS

There is nothing wrong in your code

Its just that, Media Element stops working in the background. CurrentState of the media elements gives a "Closed" when we get back to the app after pressing the start button.

You need to use a player that plays the sound even when the app goes in the background(start key press/lock key press). And BackgroundAudioPlayer follows over your requirement.

I am not very much aware with how it works but I can suggest you with some links at this point of time.

Please have a look at the BackgroundAudiolayer and also its namespace.

And a Sample

Enjoy!

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