# Switching songs - MediaPlayer lags the game

When the player encounters a boss in the game I'm working on, I want to have the music change. It seems simple enough with the MediaPlayer class to fade out the current song, switch to another, and then fade the new song in. However, at the point where the second song starts, the game freezes for a split second. The songs in question aren't particularly large either - the first song is 1.7mb and the second song is 3.1mb, both mp3 format. This is the code I'm using to do it:

protected void switchSong(GameTime gameTime)
{
if (!bossSongPlaying)
{
MediaPlayer.Volume -= ((float)gameTime.ElapsedGameTime.TotalSeconds/10);
if (MediaPlayer.Volume < 0.05f)
{
MediaPlayer.Play(bossSong);
MediaPlayer.Volume = 1.0f;
bossSongPlaying = true;
}
}
}


What can I do to eliminate that momentary hang?

It looks like you have roughly the same problem as described here: http://forums.create.msdn.com/forums/p/44169/419462.aspx

The solution there seems to be the following.

In the loading screen of your level do the following for all the songs you would like to play in the level:

MediaPlayer.Play(backgroundSong);
MediaPlayer.Pause();


This way your songs are preloaded and should not cause a stutter.

Are more solid approach would be to switch to XACT, which ables you to use more advanced features of the XNA sound engine and doesn't seem to cause problems. Other people have noted that WAV files also don't cause problems, but this could make your game very large.

• +1 For XACT. It may have some warts, but it does what you need it to do. – michael.bartnett Mar 21 '12 at 7:31
• I'd like to avoid using XACT to give the player the option of using their own mp3 folder should they not like my music. – Fibericon Mar 21 '12 at 8:14
• In that case you will have to try the suggested pre-loading trick. – Roy T. Mar 21 '12 at 10:59

I ended up using WMPlib, which seems to work a whole lot faster.