Playing Songs in Silverlight5

Apr 2, 2012 at 4:40 PM

This morning I posted (a response in another thread) about my difficulty in loading Song Content for the Silverlight5 port of my XNA game: http://silversprite.codeplex.com/discussions/343549.  To summarize: there doesn't appear to be a Content.SongReader under Silverlight5, and using the available SoundEffect content type to play background music bloated my XAP file from 1.5MB up to 13.5MB.  The source MP3 was 2.9MB, which after being compiled into a Song became 1.7MB (XNB + WMA pair).  I'm still curious whether there are any suggestions for loading this Song data.  In the mean time, I figured I'd post my work around solution of using Silverlight5's MediaElement to load and play background music.  The _filename here is relative to the ClientBin folder, where I dropped my original MP3.  Hope this is helpful to others!

// to make this run on the main UI thread
Deployment.Current.Dispatcher.BeginInvoke(() => {
    _music = new MediaElement();
    _music.Source = new Uri(_filename + ".mp3", UriKind.Relative);
    // this is how I access LayoutRoot, since running in a separate project
    Grid LayoutRoot = ((Grid((UserControl)Application.Current.RootVisual).FindName("LayoutRoot"));
    LayoutRoot.Children.Add(_music);
});

// play song
Deployment.Current.Dispatcher.BeginInvoke(() => {
    _music.Play();
});

// stop song
Deployment.Current.Dispatcher.BeginInvoke(() => {
    _music.Stop();
});