views:

22

answers:

2

I'm making a game in Silverlight, and I'd like to give it some background music. And in particular I'd like to avoid including the MP3 in the initial download (the XAP) - so that the user can start playing before the music has finished downloading.

How do I:

  • Dynamically start playing an MP3 file from a given URL
  • Have the MP3 file start playing before it has finished downloading
  • Start downloading the MP3 file without having it play (ie: preload it)
  • In such a way that the MP3 file is cached if the user returns to the page later

(I am assuming all of these things are possible?)

I am not really using XAML, by the way - so a code-based answer is appreciated.

A: 

MediaElement object supports progressive download of MP3 files. You can put MP3 files on your server and stream when needed. If you want more control over storage, you can implement you own streaming protocol by implementing MediaStreamSource.

AlexEzh
A: 

System.Windows.Controls.MediaElement is the control to use, obviously. It needs to be added to the Silverlight visual tree to work entirely correctly.

Here is the code to preload a song:

mediaElement.AutoPlay = false;
mediaElement.Source = new Uri("/content/something.mp3", UriKind.Relative);

(Music is best added to the project and set with Build Action = None, and Copy to Output Directory = Copy if newer. This will place it beside the XAP.)

This allows the song to start loading in the background without playing. To check when it has finished preloading, hook mediaElement.DownloadProgressChanged and check for mediaElement.DownloadProgress == 1. Hooking MediaFailed will tell you if the download fails.

The song can be started without waiting for the download to finish. And MediaElement will correctly cache a fully downloaded song in the browser cache.

Andrew Russell