Gijo
Gijo

Reputation: 249

WP7 background music play

In my WP7 app, I want 2 music files to run in background.I am using MediaElement to do this. I am facing two issues.

  1. how to play in background?
  2. How to loop background music?

Upvotes: 2

Views: 393

Answers (1)

PmanAce
PmanAce

Reputation: 4353

This is how I do it. Add the following:

<MediaElement x:Name="meSong" />

This is added in the constructor:

meSong.MediaEnded += new RoutedEventHandler(meSong_MediaEnded);

This is how I loop the song once it has ended:

private void meSong_MediaEnded(object sender, RoutedEventArgs e)
{
    meSong.Position = TimeSpan.Zero;
    meSong.Play();
} 

This is how I set my song:

private void SetSong(string selectedSong)
{
    if (ViewModel.IsMusicOn)
    {
        try
        {
            meSong.Stop();

            meSong.Source = new Uri(string.Format("Media/Sounds/{0}.wav", selectedSong), UriKind.Relative);
            meSong.Position = new TimeSpan(0);
            meSong.Volume = 0.5;
        }
        catch (Exception)
        {
            // nothing for now
        }
    }
}

And this is how you obviously start your music:

meSong.Play();

Upvotes: 1

Related Questions