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.
System.Windows.Controls.MediaElementis 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:
(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.DownloadProgressChangedand check formediaElement.DownloadProgress == 1. HookingMediaFailedwill 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.