Search code examples
xnaloadingplayback

XNA MediaPlayer loading music timing


I load music with the following code in my load content function:

song = Content.Load<Song>("music/game");
MediaPlayer.IsRepeating = false;
MediaPlayer.Play(song);

nothing strange there, but each round in my game is 2 minutes long and should sync up with the music (that is 2 minutes long) but the music ends betweem 2-4s early. This wouldn't be a problem if it was always the same time.

My guess is that it has something to do with load times? any advice?


Solution

  • One thing you could do is move the Content.Load<Song> to Load method and check if it is playing in the update, and if not, play. Eg,

    public void LoadContent(ConentManager content)
    {
        song = content.Load<Song>("music/game");
        gameSongStartedPlaying = false; // this variable to hold if you have starting playing this song already
        MediaPlayer.IsRepeating = false;
    }
    
    public void Update(GameTime gameTime)
    {
        if(MediaPlayer.State == MediaState.Stopped && !gameSongStartedPlaying)
        {
            MediaPlayer.Play(song);
            gameSongStartedPlaying = true;
        }
    }
    

    This should start playing the song on the first pass of the Update method rather than in the Loading phase where the song is 'playing' while all resources after Content.Load<Song> are still loading (this would be the reason your song finishes early).