1
\$\begingroup\$

I am just wondering where is the best place to start playing the background song for a game. In the loadContent() method, Draw(), or Update() methods or when I initialize it?

I am trying to make it so that the song starts playing at the same time the screen appears.

\$\endgroup\$
2
\$\begingroup\$

In "real" XNA is it safe to do so in any of the methods you listed, although I would recommend BeginRun myself, which is called once, immediately before the first call to Update.

protected override void BeginRun()
{
    MediaPlayer.Play(song);
    base.BeginRun();
}

MonoGame has historically implemented the startup sequence with subtle differences to the real XNA. But in this case it's probably quite safe to treat it like XNA. (I think at one stage it didn't even have the BeginRun method in Game - hopefully that's been fixed.)

It's totally reasonable and safe to simply do this:

bool songStarted = false;

protected override void Update(GameTime gameTime)
{
    if(!songStarted)
    {
        MediaPlayer.Play(song);
        songStarted = true;
    }

    // ...
}

Which may seem over-done in this context, but starts to make more sense when you need to have greater control over music playback (eg: starting a song at the beginning of each level).

Finally, you may be tempted to implement the above check by checking the MediaPlayer.State property each frame (instead of your own boolean). I strongly recommend not doing this, as (at least in XNA) this is a slow, blocking operation that can significantly slow down your game.

\$\endgroup\$
  • \$\begingroup\$ Is it not ok to simply play the song in loadcontent? as this is only called once just before the game is rendered. \$\endgroup\$ – Pectus Excavatum Oct 1 '13 at 12:28
  • \$\begingroup\$ LoadContent is ok (like I said - all the methods you listed are ok). But BeginRun is more semantically correct. \$\endgroup\$ – Andrew Russell Oct 1 '13 at 13:56
  • \$\begingroup\$ Ok Thanks, I am using monogame the the music is played from within a game screen (using screenmanager) so using beginrun might be a bit tricky. But I like to do things properly, so I will have a look. \$\endgroup\$ – Pectus Excavatum Oct 1 '13 at 14:05
  • \$\begingroup\$ The game screen class might provide different methods to Game, but they'll ultimately be called from somewhere in Game - so that's fine too. \$\endgroup\$ – Andrew Russell Oct 3 '13 at 7:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.