I have a C#
Console game I'm working on and I'd really like to incorporate some background music into it.
I have a function that calls the SoundPlayer and I have it playing music as anticipated. My function will be called upon certain circumstances of my game, but when it is called I would like for the game to continue. Currently, my game loops through as expected, but once it hits the playMusic()
function the game comes to a standstill until the music stops playing.
How do I make the music play in the background without interrupting my main game loop? Any thoughts on the matter will be greatly appreciated.
The music function:
public void playMusic()
{
SoundPlayer sndPlayer = new SoundPlayer();
sndPlayer.SoundLocation = Environment.CurrentDirectory + "\\Music.Wav";
sndPlayer.PlaySync();
}
My Game Loop:
int gameoverCount =0;
//Main game loop
while (gameoverCount != 1000)
{
//Select a random NPC to move
int randomNPC = StaticRandom.Instance.Next(0, npcs.characters.Count);
//Checks if the NPC has reached it's destination, if not move.
if (npcs.characters[randomNPC].destination)
{
Movement.npcMove(board, npcs.characters[randomNPC]);
}
else
{
//Gives NPC new location
npcs.characters[randomNPC].destinationX = StaticRandom.Instance.Next(3, 14);
npcs.characters[randomNPC].destinationY = StaticRandom.Instance.Next(3, 14);
npcs.characters[randomNPC].destination = true;
}
gameoverCount++;
Movement.playerMove(p1.coordX, p1.coordY, board, p1, p1.bac, p1.stepsTaken, npcs.characters[randomNPC]);
//If player is on a certain space, play music
if (board.board[p1.coordX, p1.coordY].playMusic)
{
playMusic();
}
Console.Clear();
board.showBoard();
}
What you're looking for is the Play or the PlayLooping method. As you can see in the remarks section, both these methods will play the music using a new thread. PlaySync, on the other hand, uses the current thread, which is the reason why you get the behavior you're getting.