WP7 - playing mediaelement after page is loaded

2019-09-06 15:57发布

问题:

I have this MediaElement in my xaml page:

<MediaElement 
            x:Name="soundMenu" 
            Source="Sounds/menu.wav" 
            AutoPlay="False" MediaEnded="soundMenu_MediaEnded"/>

and I want it to play when page is loaded (like background music):

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
     soundMenu.Play()
}

It doesn't work. When I click on some button and try to play music it's working but this isn't. What's wrong with this? How can I play sound after page is loaded?

P.s.: I know I must check if user is playing something. I just for now want to solve this issue:)

回答1:

It takes some time for the MediaElement to initialize. I guess in your case you try to start playing before the sound file has been loaded. Set AutoPlay to true or call the Play method in MediaOpened event handler.