Reputation:
I am trying to play background music in my app. Initially I had this:
<Application.Resources>
<MediaElement x:Key="AppSoundFile" Name="backgroundMusic" Source="track.mp3" AutoPlay="False" Volume="1" MediaEnded="LoopMusic"/>
</Application.Resources>
private void PlayMusic()
{
backgroundMusic = new MediaElement();
backgroundMusic = (MediaElement)Application.Current.Resources["AppSoundFile"];
backgroundMusic.AutoPlay = true;
backgroundMusic.Volume = 5;
backgroundMusic.Play();
}
And it was working fine.
However my app was rejected based on the notion I did not allow the users to be able to choose their own music. And since if I put it in App.xaml, user's music would be stopped automatically, so I moved the code into App.xaml.cs like this:
private void PlayMusic()
{
backgroundMusic = new MediaElement();
backgroundMusic.Source = new Uri("track.mp3", UriKind.RelativeOrAbsolute);
backgroundMusic.AutoPlay = true;
backgroundMusic.Volume = 5;
backgroundMusic.Play();
}
Now my own music won't load at all. I tried to set it to Content, back to Resource, different copy options, absolute address, relative address & about 50 other suggestions web have directed me to.
No avail.
Has anyone else incurred this kind of problem? If so how did you solve it? Help much appreciated. Thanks in advance.
Seriously microsoft, why make it so difficult?!
Upvotes: 1
Views: 1071
Reputation:
Thanks to Kookiz. I have moved PlayMusic from app.xaml.cs to MainPage.xaml.cs (because app.xaml has no LayoutRoot).
private void PlayMusic()
{
backgroundMusic = new MediaElement();
backgroundMusic.Source = new Uri("track.mp3", UriKind.RelativeOrAbsolute);
backgroundMusic.AutoPlay = true;
backgroundMusic.Volume = 1;
LayoutRoot.Children.Add(backgroundMusic);
backgroundMusic.Play();
}
Now the music is working as it should ... although with a very very slight delay.
Upvotes: 2